本文整理汇总了Golang中github.com/ttysteale/kubernetes-api/api.Resource函数的典型用法代码示例。如果您正苦于以下问题:Golang Resource函数的具体用法?Golang Resource怎么用?Golang Resource使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Resource函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: NewREST
// NewREST returns a RESTStorage object that will work against secrets.
func NewREST(opts generic.RESTOptions) *REST {
prefix := "/secrets"
newListFunc := func() runtime.Object { return &api.SecretList{} }
storageInterface := opts.Decorator(
opts.Storage, cachesize.GetWatchCacheSizeByResource(cachesize.Secrets), &api.Secret{}, prefix, secret.Strategy, newListFunc)
store := ®istry.Store{
NewFunc: func() runtime.Object { return &api.Secret{} },
NewListFunc: newListFunc,
KeyRootFunc: func(ctx api.Context) string {
return registry.NamespaceKeyRootFunc(ctx, prefix)
},
KeyFunc: func(ctx api.Context, id string) (string, error) {
return registry.NamespaceKeyFunc(ctx, prefix, id)
},
ObjectNameFunc: func(obj runtime.Object) (string, error) {
return obj.(*api.Secret).Name, nil
},
PredicateFunc: func(label labels.Selector, field fields.Selector) generic.Matcher {
return secret.Matcher(label, field)
},
QualifiedResource: api.Resource("secrets"),
DeleteCollectionWorkers: opts.DeleteCollectionWorkers,
CreateStrategy: secret.Strategy,
UpdateStrategy: secret.Strategy,
DeleteStrategy: secret.Strategy,
Storage: storageInterface,
}
return &REST{store}
}
示例2: TestCheckGeneratedNameError
func TestCheckGeneratedNameError(t *testing.T) {
expect := errors.NewNotFound(api.Resource("foos"), "bar")
if err := rest.CheckGeneratedNameError(Strategy, expect, &api.Pod{}); err != expect {
t.Errorf("NotFoundError should be ignored: %v", err)
}
expect = errors.NewAlreadyExists(api.Resource("foos"), "bar")
if err := rest.CheckGeneratedNameError(Strategy, expect, &api.Pod{}); err != expect {
t.Errorf("AlreadyExists should be returned when no GenerateName field: %v", err)
}
expect = errors.NewAlreadyExists(api.Resource("foos"), "bar")
if err := rest.CheckGeneratedNameError(Strategy, expect, &api.Pod{ObjectMeta: api.ObjectMeta{GenerateName: "foo"}}); err == nil || !errors.IsServerTimeout(err) {
t.Errorf("expected try again later error: %v", err)
}
}
示例3: existingController
// existingController verifies if the controller already exists
func (r *RollingUpdater) existingController(controller *api.ReplicationController) (*api.ReplicationController, error) {
// without rc name but generate name, there's no existing rc
if len(controller.Name) == 0 && len(controller.GenerateName) > 0 {
return nil, errors.NewNotFound(api.Resource("replicationcontrollers"), controller.Name)
}
// controller name is required to get rc back
return r.c.ReplicationControllers(controller.Namespace).Get(controller.Name)
}
示例4: TestErrorNew
func TestErrorNew(t *testing.T) {
err := NewAlreadyExists(api.Resource("tests"), "1")
if !IsAlreadyExists(err) {
t.Errorf("expected to be %s", unversioned.StatusReasonAlreadyExists)
}
if IsConflict(err) {
t.Errorf("expected to not be %s", unversioned.StatusReasonConflict)
}
if IsNotFound(err) {
t.Errorf(fmt.Sprintf("expected to not be %s", unversioned.StatusReasonNotFound))
}
if IsInvalid(err) {
t.Errorf("expected to not be %s", unversioned.StatusReasonInvalid)
}
if IsBadRequest(err) {
t.Errorf("expected to not be %s", unversioned.StatusReasonBadRequest)
}
if IsForbidden(err) {
t.Errorf("expected to not be %s", unversioned.StatusReasonForbidden)
}
if IsServerTimeout(err) {
t.Errorf("expected to not be %s", unversioned.StatusReasonServerTimeout)
}
if IsMethodNotSupported(err) {
t.Errorf("expected to not be %s", unversioned.StatusReasonMethodNotAllowed)
}
if !IsConflict(NewConflict(api.Resource("tests"), "2", errors.New("message"))) {
t.Errorf("expected to be conflict")
}
if !IsNotFound(NewNotFound(api.Resource("tests"), "3")) {
t.Errorf("expected to be %s", unversioned.StatusReasonNotFound)
}
if !IsInvalid(NewInvalid(api.Kind("Test"), "2", nil)) {
t.Errorf("expected to be %s", unversioned.StatusReasonInvalid)
}
if !IsBadRequest(NewBadRequest("reason")) {
t.Errorf("expected to be %s", unversioned.StatusReasonBadRequest)
}
if !IsForbidden(NewForbidden(api.Resource("tests"), "2", errors.New("reason"))) {
t.Errorf("expected to be %s", unversioned.StatusReasonForbidden)
}
if !IsUnauthorized(NewUnauthorized("reason")) {
t.Errorf("expected to be %s", unversioned.StatusReasonUnauthorized)
}
if !IsServerTimeout(NewServerTimeout(api.Resource("tests"), "reason", 0)) {
t.Errorf("expected to be %s", unversioned.StatusReasonServerTimeout)
}
if time, ok := SuggestsClientDelay(NewServerTimeout(api.Resource("tests"), "doing something", 10)); time != 10 || !ok {
t.Errorf("expected to be %s", unversioned.StatusReasonServerTimeout)
}
if time, ok := SuggestsClientDelay(NewTimeoutError("test reason", 10)); time != 10 || !ok {
t.Errorf("expected to be %s", unversioned.StatusReasonTimeout)
}
if !IsMethodNotSupported(NewMethodNotSupported(api.Resource("foos"), "delete")) {
t.Errorf("expected to be %s", unversioned.StatusReasonMethodNotAllowed)
}
}
示例5: TestSyncBatchIgnoresNotFound
func TestSyncBatchIgnoresNotFound(t *testing.T) {
client := fake.Clientset{}
syncer := newTestManager(&client)
client.AddReactor("get", "pods", func(action core.Action) (bool, runtime.Object, error) {
return true, nil, errors.NewNotFound(api.Resource("pods"), "test-pod")
})
syncer.SetPodStatus(getTestPod(), getRandomPodStatus())
syncer.testSyncBatch()
verifyActions(t, syncer.kubeClient, []core.Action{
core.GetActionImpl{ActionImpl: core.ActionImpl{Verb: "get", Resource: unversioned.GroupVersionResource{Resource: "pods"}}},
})
}
示例6: GetNode
func (r *NodeRegistry) GetNode(ctx api.Context, nodeID string) (*api.Node, error) {
r.Lock()
defer r.Unlock()
if r.Err != nil {
return nil, r.Err
}
for _, node := range r.Nodes.Items {
if node.Name == nodeID {
return &node, nil
}
}
return nil, errors.NewNotFound(api.Resource("nodes"), nodeID)
}
示例7: timeout
func (tw *baseTimeoutWriter) timeout(msg string) {
tw.mu.Lock()
defer tw.mu.Unlock()
if !tw.wroteHeader && !tw.hijacked {
tw.w.WriteHeader(http.StatusGatewayTimeout)
if msg != "" {
tw.w.Write([]byte(msg))
} else {
enc := json.NewEncoder(tw.w)
enc.Encode(errors.NewServerTimeout(api.Resource(""), "", 0))
}
}
tw.timedOut = true
}
示例8: TestGenericHttpResponseCheckerLimitReader
func TestGenericHttpResponseCheckerLimitReader(t *testing.T) {
responseChecker := NewGenericHttpResponseChecker(api.Resource("pods"), "foo")
excessedString := strings.Repeat("a", (maxReadLength + 10000))
resp := &http.Response{
Body: ioutil.NopCloser(bytes.NewBufferString(excessedString)),
StatusCode: http.StatusBadRequest,
}
err := responseChecker.Check(resp)
if err == nil {
t.Error("unexpected non-error")
}
if len(err.Error()) != maxReadLength {
t.Errorf("expected lenth of error message: %d, saw: %d", maxReadLength, len(err.Error()))
}
}
示例9: TestGenericHttpResponseChecker
func TestGenericHttpResponseChecker(t *testing.T) {
responseChecker := NewGenericHttpResponseChecker(api.Resource("pods"), "foo")
tests := []struct {
resp *http.Response
expectError bool
expected error
name string
}{
{
resp: &http.Response{
Body: ioutil.NopCloser(bytes.NewBufferString("Success")),
StatusCode: http.StatusOK,
},
expectError: false,
name: "ok",
},
{
resp: &http.Response{
Body: ioutil.NopCloser(bytes.NewBufferString("Invalid request.")),
StatusCode: http.StatusBadRequest,
},
expectError: true,
expected: errors.NewBadRequest("Invalid request."),
name: "bad request",
},
{
resp: &http.Response{
Body: ioutil.NopCloser(bytes.NewBufferString("Pod does not exist.")),
StatusCode: http.StatusInternalServerError,
},
expectError: true,
expected: errors.NewInternalError(fmt.Errorf("%s", "Pod does not exist.")),
name: "internal server error",
},
}
for _, test := range tests {
err := responseChecker.Check(test.resp)
if test.expectError && err == nil {
t.Error("unexpected non-error")
}
if !test.expectError && err != nil {
t.Errorf("unexpected error: %v", err)
}
if test.expectError && !reflect.DeepEqual(err, test.expected) {
t.Errorf("expected: %s, saw: %s", test.expected, err)
}
}
}
示例10: NewREST
// NewREST returns a RESTStorage object that will work with ConfigMap objects.
func NewREST(opts generic.RESTOptions) *REST {
prefix := "/configmaps"
newListFunc := func() runtime.Object { return &api.ConfigMapList{} }
storageInterface := opts.Decorator(
opts.Storage, 100, &api.ConfigMap{}, prefix, configmap.Strategy, newListFunc)
store := ®istry.Store{
NewFunc: func() runtime.Object {
return &api.ConfigMap{}
},
// NewListFunc returns an object to store results of an etcd list.
NewListFunc: newListFunc,
// Produces a path that etcd understands, to the root of the resource
// by combining the namespace in the context with the given prefix.
KeyRootFunc: func(ctx api.Context) string {
return registry.NamespaceKeyRootFunc(ctx, prefix)
},
// Produces a path that etcd understands, to the resource by combining
// the namespace in the context with the given prefix
KeyFunc: func(ctx api.Context, name string) (string, error) {
return registry.NamespaceKeyFunc(ctx, prefix, name)
},
// Retrieves the name field of a ConfigMap object.
ObjectNameFunc: func(obj runtime.Object) (string, error) {
return obj.(*api.ConfigMap).Name, nil
},
// Matches objects based on labels/fields for list and watch
PredicateFunc: configmap.MatchConfigMap,
QualifiedResource: api.Resource("configmaps"),
DeleteCollectionWorkers: opts.DeleteCollectionWorkers,
CreateStrategy: configmap.Strategy,
UpdateStrategy: configmap.Strategy,
DeleteStrategy: configmap.Strategy,
Storage: storageInterface,
}
return &REST{store}
}
示例11: Update
func (p *testPatcher) Update(ctx api.Context, name string, objInfo rest.UpdatedObjectInfo) (runtime.Object, bool, error) {
currentPod := p.startingPod
if p.numUpdates > 0 {
currentPod = p.updatePod
}
p.numUpdates++
obj, err := objInfo.UpdatedObject(ctx, currentPod)
if err != nil {
return nil, false, err
}
inPod := obj.(*api.Pod)
if inPod.ResourceVersion != p.updatePod.ResourceVersion {
return nil, false, apierrors.NewConflict(api.Resource("pods"), inPod.Name, fmt.Errorf("existing %v, new %v", p.updatePod.ResourceVersion, inPod.ResourceVersion))
}
return inPod, false, nil
}
示例12: Create
func (m *FakeNodeHandler) Create(node *api.Node) (*api.Node, error) {
m.createLock.Lock()
defer func() {
m.RequestCount++
m.createLock.Unlock()
}()
for _, n := range m.Existing {
if n.Name == node.Name {
return nil, apierrors.NewAlreadyExists(api.Resource("nodes"), node.Name)
}
}
if m.CreateHook == nil || m.CreateHook(m, node) {
nodeCopy := *node
m.CreatedNodes = append(m.CreatedNodes, &nodeCopy)
return node, nil
} else {
return nil, errors.New("Create error.")
}
}
示例13: NewStorage
// NewREST returns a RESTStorage object that will work against nodes.
func NewStorage(opts generic.RESTOptions, connection client.ConnectionInfoGetter, proxyTransport http.RoundTripper) NodeStorage {
prefix := "/minions"
newListFunc := func() runtime.Object { return &api.NodeList{} }
storageInterface := opts.Decorator(
opts.Storage, cachesize.GetWatchCacheSizeByResource(cachesize.Nodes), &api.Node{}, prefix, node.Strategy, newListFunc)
store := ®istry.Store{
NewFunc: func() runtime.Object { return &api.Node{} },
NewListFunc: newListFunc,
KeyRootFunc: func(ctx api.Context) string {
return prefix
},
KeyFunc: func(ctx api.Context, name string) (string, error) {
return registry.NoNamespaceKeyFunc(ctx, prefix, name)
},
ObjectNameFunc: func(obj runtime.Object) (string, error) {
return obj.(*api.Node).Name, nil
},
PredicateFunc: node.MatchNode,
QualifiedResource: api.Resource("nodes"),
DeleteCollectionWorkers: opts.DeleteCollectionWorkers,
CreateStrategy: node.Strategy,
UpdateStrategy: node.Strategy,
DeleteStrategy: node.Strategy,
ExportStrategy: node.Strategy,
Storage: storageInterface,
}
statusStore := *store
statusStore.UpdateStrategy = node.StatusStrategy
nodeREST := &REST{store, connection, proxyTransport}
return NodeStorage{
Node: nodeREST,
Status: &StatusREST{store: &statusStore},
Proxy: &noderest.ProxyREST{Store: store, Connection: client.ConnectionInfoGetter(nodeREST), ProxyTransport: proxyTransport},
}
}
示例14: NewREST
// NewREST returns a RESTStorage object that will work against namespaces.
func NewREST(opts generic.RESTOptions) (*REST, *StatusREST, *FinalizeREST) {
prefix := "/namespaces"
newListFunc := func() runtime.Object { return &api.NamespaceList{} }
storageInterface := opts.Decorator(
opts.Storage, cachesize.GetWatchCacheSizeByResource(cachesize.Namespaces), &api.Namespace{}, prefix, namespace.Strategy, newListFunc)
store := ®istry.Store{
NewFunc: func() runtime.Object { return &api.Namespace{} },
NewListFunc: newListFunc,
KeyRootFunc: func(ctx api.Context) string {
return prefix
},
KeyFunc: func(ctx api.Context, name string) (string, error) {
return registry.NoNamespaceKeyFunc(ctx, prefix, name)
},
ObjectNameFunc: func(obj runtime.Object) (string, error) {
return obj.(*api.Namespace).Name, nil
},
PredicateFunc: func(label labels.Selector, field fields.Selector) generic.Matcher {
return namespace.MatchNamespace(label, field)
},
QualifiedResource: api.Resource("namespaces"),
DeleteCollectionWorkers: opts.DeleteCollectionWorkers,
CreateStrategy: namespace.Strategy,
UpdateStrategy: namespace.Strategy,
DeleteStrategy: namespace.Strategy,
ReturnDeletedObject: true,
Storage: storageInterface,
}
statusStore := *store
statusStore.UpdateStrategy = namespace.StatusStrategy
finalizeStore := *store
finalizeStore.UpdateStrategy = namespace.FinalizeStrategy
return &REST{Store: store, status: &statusStore}, &StatusREST{store: &statusStore}, &FinalizeREST{store: &finalizeStore}
}
示例15: TestDeleteAllNotFound
func TestDeleteAllNotFound(t *testing.T) {
_, svc, _ := testData()
f, tf, codec := NewAPIFactory()
// Add an item to the list which will result in a 404 on delete
svc.Items = append(svc.Items, api.Service{ObjectMeta: api.ObjectMeta{Name: "foo"}})
notFoundError := &errors.NewNotFound(api.Resource("services"), "foo").ErrStatus
tf.Printer = &testPrinter{}
tf.Client = &fake.RESTClient{
Codec: codec,
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
switch p, m := req.URL.Path, req.Method; {
case p == "/namespaces/test/services" && m == "GET":
return &http.Response{StatusCode: 200, Header: defaultHeader(), Body: objBody(codec, svc)}, nil
case p == "/namespaces/test/services/foo" && m == "DELETE":
return &http.Response{StatusCode: 404, Header: defaultHeader(), Body: objBody(codec, notFoundError)}, nil
case p == "/namespaces/test/services/baz" && m == "DELETE":
return &http.Response{StatusCode: 200, Header: defaultHeader(), Body: objBody(codec, &svc.Items[0])}, nil
default:
t.Fatalf("unexpected request: %#v\n%#v", req.URL, req)
return nil, nil
}
}),
}
tf.Namespace = "test"
buf := bytes.NewBuffer([]byte{})
cmd := NewCmdDelete(f, buf)
cmd.Flags().Set("all", "true")
cmd.Flags().Set("cascade", "false")
// Make sure we can explicitly choose to fail on NotFound errors, even with --all
cmd.Flags().Set("ignore-not-found", "false")
cmd.Flags().Set("output", "name")
err := RunDelete(f, buf, cmd, []string{"services"}, &DeleteOptions{})
if err == nil || !errors.IsNotFound(err) {
t.Errorf("unexpected error: expected NotFound, got %v", err)
}
}