本文整理汇总了Golang中k8s/io/kubernetes/pkg/api/meta.NewAccessor函数的典型用法代码示例。如果您正苦于以下问题:Golang NewAccessor函数的具体用法?Golang NewAccessor怎么用?Golang NewAccessor使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewAccessor函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Admit
// Admit admits resources into cluster that do not violate any defined LimitRange in the namespace
func (l *limitRanger) Admit(a admission.Attributes) (err error) {
// Ignore all calls to subresources
if a.GetSubresource() != "" {
return nil
}
obj := a.GetObject()
name := "Unknown"
if obj != nil {
name, _ = meta.NewAccessor().Name(obj)
if len(name) == 0 {
name, _ = meta.NewAccessor().GenerateName(obj)
}
}
key := &api.LimitRange{
ObjectMeta: api.ObjectMeta{
Namespace: a.GetNamespace(),
Name: "",
},
}
items, err := l.indexer.Index("namespace", key)
if err != nil {
return admission.NewForbidden(a, fmt.Errorf("Unable to %s %v at this time because there was an error enforcing limit ranges", a.GetOperation(), a.GetResource()))
}
// if there are no items held in our indexer, check our live-lookup LRU, if that misses, do the live lookup to prime it.
if len(items) == 0 {
lruItemObj, ok := l.liveLookupCache.Get(a.GetNamespace())
if !ok || lruItemObj.(liveLookupEntry).expiry.Before(time.Now()) {
liveList, err := l.client.Core().LimitRanges(a.GetNamespace()).List(api.ListOptions{})
if err != nil {
return admission.NewForbidden(a, err)
}
newEntry := liveLookupEntry{expiry: time.Now().Add(l.liveTTL)}
for i := range liveList.Items {
newEntry.items = append(newEntry.items, &liveList.Items[i])
}
l.liveLookupCache.Add(a.GetNamespace(), newEntry)
lruItemObj = newEntry
}
lruEntry := lruItemObj.(liveLookupEntry)
for i := range lruEntry.items {
items = append(items, lruEntry.items[i])
}
}
// ensure it meets each prescribed min/max
for i := range items {
limitRange := items[i].(*api.LimitRange)
err = l.limitFunc(limitRange, a.GetResource().Resource, a.GetObject())
if err != nil {
return admission.NewForbidden(a, err)
}
}
return nil
}
示例2: newExternalScheme
func newExternalScheme() (*runtime.Scheme, meta.RESTMapper, runtime.Codec) {
scheme := runtime.NewScheme()
scheme.AddKnownTypeWithName(internalGV.WithKind("Type"), &internalType{})
scheme.AddKnownTypeWithName(unlikelyGV.WithKind("Type"), &externalType{})
//This tests that kubectl will not confuse the external scheme with the internal scheme, even when they accidentally have versions of the same name.
scheme.AddKnownTypeWithName(validVersionGV.WithKind("Type"), &ExternalType2{})
codecs := serializer.NewCodecFactory(scheme)
codec := codecs.LegacyCodec(unlikelyGV)
mapper := meta.NewDefaultRESTMapper([]unversioned.GroupVersion{unlikelyGV, validVersionGV}, func(version unversioned.GroupVersion) (*meta.VersionInterfaces, error) {
return &meta.VersionInterfaces{
ObjectConvertor: scheme,
MetadataAccessor: meta.NewAccessor(),
}, versionErrIfFalse(version == validVersionGV || version == unlikelyGV)
})
for _, gv := range []unversioned.GroupVersion{unlikelyGV, validVersionGV} {
for kind := range scheme.KnownTypes(gv) {
gvk := gv.WithKind(kind)
scope := meta.RESTScopeNamespace
mapper.Add(gvk, scope)
}
}
return scheme, mapper, codec
}
示例3: TestBulkActionCompact
func TestBulkActionCompact(t *testing.T) {
bt := &bulkTester{
mapping: &meta.RESTMapping{
MetadataAccessor: meta.NewAccessor(),
},
}
out, err := &bytes.Buffer{}, &bytes.Buffer{}
bulk := Bulk{Mapper: bt, Op: bt.Record}
b := &BulkAction{Bulk: bulk, Output: "", Out: out, ErrOut: err}
b.Compact()
b2 := b.WithMessage("test1", "test2")
in := &kapi.Pod{ObjectMeta: kapi.ObjectMeta{Name: "obj1"}}
if errs := b2.Run(&kapi.List{Items: []runtime.Object{in}}, "test_namespace"); len(errs) != 0 {
t.Fatal(errs)
}
if !reflect.DeepEqual(bt.infos, []runtime.Object{in}) {
t.Fatalf("unexpected: %#v", bt.infos)
}
if !reflect.DeepEqual(bt.recorded, []runtime.Object{in}) {
t.Fatalf("unexpected: %#v", bt.recorded)
}
if out.String() != `` {
t.Fatalf("unexpected: %s", out.String())
}
if err.String() != `` {
t.Fatalf("unexpected: %s", err.String())
}
}
示例4: describerMap
func describerMap(c *client.Client, kclient kclient.Interface, host string) map[unversioned.GroupKind]kctl.Describer {
m := map[unversioned.GroupKind]kctl.Describer{
buildapi.Kind("Build"): &BuildDescriber{c, kclient},
buildapi.Kind("BuildConfig"): &BuildConfigDescriber{c, host},
deployapi.Kind("DeploymentConfig"): &DeploymentConfigDescriber{c, kclient, nil},
authorizationapi.Kind("Identity"): &IdentityDescriber{c},
imageapi.Kind("Image"): &ImageDescriber{c},
imageapi.Kind("ImageStream"): &ImageStreamDescriber{c},
imageapi.Kind("ImageStreamTag"): &ImageStreamTagDescriber{c},
imageapi.Kind("ImageStreamImage"): &ImageStreamImageDescriber{c},
routeapi.Kind("Route"): &RouteDescriber{c, kclient},
projectapi.Kind("Project"): &ProjectDescriber{c, kclient},
templateapi.Kind("Template"): &TemplateDescriber{c, meta.NewAccessor(), kapi.Scheme, nil},
authorizationapi.Kind("Policy"): &PolicyDescriber{c},
authorizationapi.Kind("PolicyBinding"): &PolicyBindingDescriber{c},
authorizationapi.Kind("RoleBinding"): &RoleBindingDescriber{c},
authorizationapi.Kind("Role"): &RoleDescriber{c},
authorizationapi.Kind("ClusterPolicy"): &ClusterPolicyDescriber{c},
authorizationapi.Kind("ClusterPolicyBinding"): &ClusterPolicyBindingDescriber{c},
authorizationapi.Kind("ClusterRoleBinding"): &ClusterRoleBindingDescriber{c},
authorizationapi.Kind("ClusterRole"): &ClusterRoleDescriber{c},
oauthapi.Kind("OAuthAccessToken"): &OAuthAccessTokenDescriber{c},
userapi.Kind("User"): &UserDescriber{c},
userapi.Kind("Group"): &GroupDescriber{c.Groups()},
userapi.Kind("UserIdentityMapping"): &UserIdentityMappingDescriber{c},
quotaapi.Kind("ClusterResourceQuota"): &ClusterQuotaDescriber{c},
quotaapi.Kind("AppliedClusterResourceQuota"): &AppliedClusterQuotaDescriber{c},
}
return m
}
示例5: processData
func processData(jsonData []byte, format string, templateName string, ns string, c *k8sclient.Client, oc *oclient.Client, pv bool) {
// lets check if its an RC / ReplicaSet or something
o, groupVersionKind, err := api.Codecs.UniversalDeserializer().Decode(jsonData, nil, nil)
if err != nil {
printResult(templateName, Failure, err)
} else {
kind := groupVersionKind.Kind
//util.Infof("Processing resource of kind: %s version: %s\n", kind, groupVersionKind.Version)
if len(kind) <= 0 {
printResult(templateName, Failure, fmt.Errorf("Could not find kind from json %s", string(jsonData)))
} else {
accessor := meta.NewAccessor()
ons, err := accessor.Namespace(o)
if err == nil && len(ons) > 0 {
util.Infof("Found namespace on kind %s of %s", kind, ons)
ns = ons
err := ensureNamespaceExists(c, oc, ns)
if err != nil {
printErr(err)
}
}
if !pv {
if kind == "PersistentVolumeClaim" {
return
}
jsonData = removePVCVolumes(jsonData, format, templateName, kind)
}
err = processResource(c, jsonData, ns, kind)
if err != nil {
printResult(templateName, Failure, err)
}
}
}
}
示例6: newExternalScheme
func newExternalScheme() (*runtime.Scheme, meta.RESTMapper, runtime.Codec) {
scheme := runtime.NewScheme()
scheme.AddKnownTypeWithName("", "Type", &internalType{})
scheme.AddKnownTypeWithName("unlikelyversion", "Type", &externalType{})
//This tests that kubectl will not confuse the external scheme with the internal scheme, even when they accidentally have versions of the same name.
scheme.AddKnownTypeWithName(testapi.Version(), "Type", &ExternalType2{})
codec := runtime.CodecFor(scheme, "unlikelyversion")
validVersion := testapi.Version()
mapper := meta.NewDefaultRESTMapper("apitest", []string{"unlikelyversion", validVersion}, func(version string) (*meta.VersionInterfaces, error) {
return &meta.VersionInterfaces{
Codec: runtime.CodecFor(scheme, version),
ObjectConvertor: scheme,
MetadataAccessor: meta.NewAccessor(),
}, versionErrIfFalse(version == validVersion || version == "unlikelyversion")
})
for _, version := range []string{"unlikelyversion", validVersion} {
for kind := range scheme.KnownTypes(version) {
mixedCase := false
scope := meta.RESTScopeNamespace
mapper.Add(scope, kind, version, mixedCase)
}
}
return scheme, mapper, codec
}
示例7: describerMap
func describerMap(c *client.Client, kclient kclient.Interface, host string) map[string]kctl.Describer {
m := map[string]kctl.Describer{
"Build": &BuildDescriber{c, kclient},
"BuildConfig": &BuildConfigDescriber{c, host},
"BuildLog": &BuildLogDescriber{c},
"DeploymentConfig": NewDeploymentConfigDescriber(c, kclient),
"Identity": &IdentityDescriber{c},
"Image": &ImageDescriber{c},
"ImageStream": &ImageStreamDescriber{c},
"ImageStreamTag": &ImageStreamTagDescriber{c},
"ImageStreamImage": &ImageStreamImageDescriber{c},
"Route": &RouteDescriber{c},
"Project": &ProjectDescriber{c, kclient},
"Template": &TemplateDescriber{c, meta.NewAccessor(), kapi.Scheme, nil},
"Policy": &PolicyDescriber{c},
"PolicyBinding": &PolicyBindingDescriber{c},
"RoleBinding": &RoleBindingDescriber{c},
"Role": &RoleDescriber{c},
"ClusterPolicy": &ClusterPolicyDescriber{c},
"ClusterPolicyBinding": &ClusterPolicyBindingDescriber{c},
"ClusterRoleBinding": &ClusterRoleBindingDescriber{c},
"ClusterRole": &ClusterRoleDescriber{c},
"User": &UserDescriber{c},
"Group": &GroupDescriber{c.Groups()},
"UserIdentityMapping": &UserIdentityMappingDescriber{c},
}
return m
}
示例8: Admit
// Admit admits resources into cluster that do not violate any defined LimitRange in the namespace
func (l *limitRanger) Admit(a admission.Attributes) (err error) {
// Ignore all calls to subresources
if a.GetSubresource() != "" {
return nil
}
obj := a.GetObject()
resource := a.GetResource()
name := "Unknown"
if obj != nil {
name, _ = meta.NewAccessor().Name(obj)
if len(name) == 0 {
name, _ = meta.NewAccessor().GenerateName(obj)
}
}
key := &api.LimitRange{
ObjectMeta: api.ObjectMeta{
Namespace: a.GetNamespace(),
Name: "",
},
}
items, err := l.indexer.Index("namespace", key)
if err != nil {
return admission.NewForbidden(a, fmt.Errorf("Unable to %s %s at this time because there was an error enforcing limit ranges", a.GetOperation(), resource))
}
if len(items) == 0 {
return nil
}
// ensure it meets each prescribed min/max
for i := range items {
limitRange := items[i].(*api.LimitRange)
err = l.limitFunc(limitRange, a.GetResource(), a.GetObject())
if err != nil {
return admission.NewForbidden(a, err)
}
}
return nil
}
示例9: TestResourceVersionerOfAPI
func TestResourceVersionerOfAPI(t *testing.T) {
type T struct {
runtime.Object
Expected string
}
testCases := map[string]T{
"empty api object": {&MyAPIObject{}, ""},
"api object with version": {&MyAPIObject{TypeMeta: InternalTypeMeta{ResourceVersion: "1"}}, "1"},
"pointer to api object with version": {&MyAPIObject{TypeMeta: InternalTypeMeta{ResourceVersion: "1"}}, "1"},
}
versioning := meta.NewAccessor()
for key, testCase := range testCases {
actual, err := versioning.ResourceVersion(testCase.Object)
if err != nil {
t.Errorf("%s: unexpected error %#v", key, err)
}
if actual != testCase.Expected {
t.Errorf("%s: expected %v, got %v", key, testCase.Expected, actual)
}
}
failingCases := map[string]struct {
runtime.Object
Expected string
}{
"not a valid object to try": {&MyIncorrectlyMarkedAsAPIObject{}, "1"},
}
for key, testCase := range failingCases {
_, err := versioning.ResourceVersion(testCase.Object)
if err == nil {
t.Errorf("%s: expected error, got nil", key)
}
}
setCases := map[string]struct {
runtime.Object
Expected string
}{
"pointer to api object with version": {&MyAPIObject{TypeMeta: InternalTypeMeta{ResourceVersion: "1"}}, "1"},
}
for key, testCase := range setCases {
if err := versioning.SetResourceVersion(testCase.Object, "5"); err != nil {
t.Errorf("%s: unexpected error %#v", key, err)
}
actual, err := versioning.ResourceVersion(testCase.Object)
if err != nil {
t.Errorf("%s: unexpected error %#v", key, err)
}
if actual != "5" {
t.Errorf("%s: expected %v, got %v", key, "5", actual)
}
}
}
示例10: makeInterfacesFor
func makeInterfacesFor(versionList []unversioned.GroupVersion) func(version unversioned.GroupVersion) (*meta.VersionInterfaces, error) {
accessor := meta.NewAccessor()
return func(version unversioned.GroupVersion) (*meta.VersionInterfaces, error) {
for ix := range versionList {
if versionList[ix].String() == version.String() {
return &meta.VersionInterfaces{
ObjectConvertor: thirdpartyresourcedata.NewThirdPartyObjectConverter(api.Scheme),
MetadataAccessor: accessor,
}, nil
}
}
return nil, fmt.Errorf("unsupported storage version: %s (valid: %v)", version, versionList)
}
}
示例11: Enable
// 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 := []schema.GroupVersion{}
for _, v := range gmf.prioritizedVersionList {
if !m.IsAllowedVersion(v) {
continue
}
externalVersions = append(externalVersions, v)
if err := m.EnableVersions(v); err != nil {
return err
}
gmf.VersionArgs[v.Version].AddToScheme(scheme)
}
if len(externalVersions) == 0 {
glog.V(4).Infof("No version is registered for group %v", gmf.GroupArgs.GroupName)
return nil
}
if gmf.GroupArgs.AddInternalObjectsToScheme != nil {
gmf.GroupArgs.AddInternalObjectsToScheme(scheme)
}
preferredExternalVersion := externalVersions[0]
accessor := meta.NewAccessor()
groupMeta := &apimachinery.GroupMeta{
GroupVersion: preferredExternalVersion,
GroupVersions: externalVersions,
SelfLinker: runtime.SelfLinker(accessor),
}
for _, v := range externalVersions {
gvf := gmf.VersionArgs[v.Version]
if err := groupMeta.AddVersionInterfaces(
schema.GroupVersion{Group: gvf.GroupName, Version: gvf.VersionName},
&meta.VersionInterfaces{
ObjectConvertor: scheme,
MetadataAccessor: accessor,
},
); err != nil {
return err
}
}
groupMeta.InterfacesFor = groupMeta.DefaultInterfacesFor
groupMeta.RESTMapper = gmf.newRESTMapper(scheme, externalVersions, groupMeta)
if err := m.RegisterGroup(*groupMeta); err != nil {
return err
}
return nil
}
示例12: registerThirdPartyResources
// registerThirdPartyResources inspects the discovery endpoint to find thirdpartyresources in the discovery doc
// and then registers them with the apimachinery code. I think this is done so that scheme/codec stuff works,
// but I really don't know. Feels like this code should go away once kubectl is completely generic for generic
// CRUD
func registerThirdPartyResources(discoveryClient discovery.DiscoveryInterface) error {
var versions []unversioned.GroupVersion
var gvks []unversioned.GroupVersionKind
var err error
retries := 3
for i := 0; i < retries; i++ {
versions, gvks, err = GetThirdPartyGroupVersions(discoveryClient)
// Retry if we got a NotFound error, because user may delete
// a thirdparty group when the GetThirdPartyGroupVersions is
// running.
if err == nil || !apierrors.IsNotFound(err) {
break
}
}
if err != nil {
return err
}
groupsMap := map[string][]unversioned.GroupVersion{}
for _, version := range versions {
groupsMap[version.Group] = append(groupsMap[version.Group], version)
}
for group, versionList := range groupsMap {
preferredExternalVersion := versionList[0]
thirdPartyMapper, err := kubectl.NewThirdPartyResourceMapper(versionList, getGroupVersionKinds(gvks, group))
if err != nil {
return err
}
accessor := meta.NewAccessor()
groupMeta := apimachinery.GroupMeta{
GroupVersion: preferredExternalVersion,
GroupVersions: versionList,
RESTMapper: thirdPartyMapper,
SelfLinker: runtime.SelfLinker(accessor),
InterfacesFor: makeInterfacesFor(versionList),
}
if err := registered.RegisterGroup(groupMeta); err != nil {
return err
}
registered.AddThirdPartyAPIGroupVersions(versionList...)
}
return nil
}
示例13: TestTypeMetaSelfLinker
func TestTypeMetaSelfLinker(t *testing.T) {
table := map[string]struct {
obj runtime.Object
expect string
try string
succeed bool
}{
"normal": {
obj: &MyAPIObject{TypeMeta: InternalTypeMeta{SelfLink: "foobar"}},
expect: "foobar",
try: "newbar",
succeed: true,
},
"fail": {
obj: &MyIncorrectlyMarkedAsAPIObject{},
succeed: false,
},
}
linker := runtime.SelfLinker(meta.NewAccessor())
for name, item := range table {
got, err := linker.SelfLink(item.obj)
if e, a := item.succeed, err == nil; e != a {
t.Errorf("%v: expected %v, got %v", name, e, a)
}
if e, a := item.expect, got; item.succeed && e != a {
t.Errorf("%v: expected %v, got %v", name, e, a)
}
err = linker.SetSelfLink(item.obj, item.try)
if e, a := item.succeed, err == nil; e != a {
t.Errorf("%v: expected %v, got %v", name, e, a)
}
if item.succeed {
got, err := linker.SelfLink(item.obj)
if err != nil {
t.Errorf("%v: expected no err, got %v", name, err)
}
if e, a := item.try, got; e != a {
t.Errorf("%v: expected %v, got %v", name, e, a)
}
}
}
}
示例14: TestBulk
func TestBulk(t *testing.T) {
bt := &bulkTester{
mapping: &meta.RESTMapping{
MetadataAccessor: meta.NewAccessor(),
},
}
b := Bulk{Mapper: bt, Op: bt.Record}
in := &kapi.Pod{}
if errs := b.Run(&kapi.List{Items: []runtime.Object{in}}, "test_namespace"); len(errs) > 0 {
t.Fatal(errs)
}
if !reflect.DeepEqual(bt.infos, []runtime.Object{in}) {
t.Fatalf("unexpected: %#v", bt.infos)
}
if !reflect.DeepEqual(bt.recorded, []runtime.Object{in}) {
t.Fatalf("unexpected: %#v", bt.recorded)
}
}
示例15: HasJenkinsService
// HasJenkinsService searches the template items and return true if the expected
// Jenkins service is contained in template.
func (t *PipelineTemplate) HasJenkinsService(items *kapi.List) bool {
accessor := meta.NewAccessor()
for _, item := range items.Items {
kind, _, err := kapi.Scheme.ObjectKind(item)
if err != nil {
glog.Infof("Error checking Jenkins service kind: %v", err)
return false
}
name, err := accessor.Name(item)
if err != nil {
glog.Infof("Error checking Jenkins service name: %v", err)
return false
}
glog.Infof("Jenkins Pipeline template object %q with name %q", name, kind.Kind)
if name == t.Config.ServiceName && kind.Kind == "Service" {
return true
}
}
return false
}