本文整理汇总了Golang中github.com/GoogleCloudPlatform/kubernetes/pkg/api/errors.IsNotFound函数的典型用法代码示例。如果您正苦于以下问题:Golang IsNotFound函数的具体用法?Golang IsNotFound怎么用?Golang IsNotFound使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了IsNotFound函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: ReplaceChangedRoles
func (o *reconcileClusterOptions) ReplaceChangedRoles(changedRoles []*authorizationapi.ClusterRole) error {
for i := range changedRoles {
role, err := o.RoleClient.Get(changedRoles[i].Name)
if err != nil && !kapierrors.IsNotFound(err) {
return err
}
if kapierrors.IsNotFound(err) {
createdRole, err := o.RoleClient.Create(changedRoles[i])
if err != nil {
return err
}
fmt.Fprintf(o.Out, "clusterrole/%s\n", createdRole.Name)
continue
}
role.Rules = changedRoles[i].Rules
updatedRole, err := o.RoleClient.Update(role)
if err != nil {
return err
}
fmt.Fprintf(o.Out, "clusterrole/%s\n", updatedRole.Name)
}
return nil
}
示例2: TestEtcdCreateBindingNoPod
// Ensure that when scheduler creates a binding for a pod that has already been deleted
// by the API server, API server returns not-found error.
func TestEtcdCreateBindingNoPod(t *testing.T) {
registry, bindingRegistry, _, fakeClient, _ := newStorage(t)
ctx := api.NewDefaultContext()
fakeClient.TestIndex = true
key, _ := registry.KeyFunc(ctx, "foo")
fakeClient.Data[key] = tools.EtcdResponseWithError{
R: &etcd.Response{
Node: nil,
},
E: tools.EtcdErrorNotFound,
}
// Assume that a pod has undergone the following:
// - Create (apiserver)
// - Schedule (scheduler)
// - Delete (apiserver)
_, err := bindingRegistry.Create(ctx, &api.Binding{
ObjectMeta: api.ObjectMeta{Namespace: api.NamespaceDefault, Name: "foo"},
Target: api.ObjectReference{Name: "machine"},
})
if err == nil {
t.Fatalf("Expected not-found-error but got nothing")
}
if !errors.IsNotFound(etcderrors.InterpretGetError(err, "Pod", "foo")) {
t.Fatalf("Unexpected error returned: %#v", err)
}
_, err = registry.Get(ctx, "foo")
if err == nil {
t.Fatalf("Expected not-found-error but got nothing")
}
if !errors.IsNotFound(etcderrors.InterpretGetError(err, "Pod", "foo")) {
t.Fatalf("Unexpected error: %v", err)
}
}
示例3: CancelBuild
// CancelBuild updates a build status to Cancelled, after its associated pod is deleted.
func (bc *BuildController) CancelBuild(build *buildapi.Build) error {
if !isBuildCancellable(build) {
glog.V(4).Infof("Build %s/%s can be cancelled only if it has pending/running status, not %s.", build.Namespace, build.Name, build.Status.Phase)
return nil
}
glog.V(4).Infof("Cancelling Build %s/%s.", build.Namespace, build.Name)
pod, err := bc.PodManager.GetPod(build.Namespace, buildutil.GetBuildPodName(build))
if err != nil {
if !errors.IsNotFound(err) {
return fmt.Errorf("Failed to get Pod for build %s/%s: %v", build.Namespace, build.Name, err)
}
} else {
err := bc.PodManager.DeletePod(build.Namespace, pod)
if err != nil && !errors.IsNotFound(err) {
return fmt.Errorf("Couldn't delete Build Pod %s/%s: %v", build.Namespace, pod.Name, err)
}
}
build.Status.Phase = buildapi.BuildPhaseCancelled
now := util.Now()
build.Status.CompletionTimestamp = &now
if err := bc.BuildUpdater.Update(build.Namespace, build); err != nil {
return fmt.Errorf("Failed to update Build %s/%s: %v", build.Namespace, build.Name, err)
}
glog.V(4).Infof("Build %s/%s was successfully cancelled.", build.Namespace, build.Name)
return nil
}
示例4: TestMinionRegistryREST
func TestMinionRegistryREST(t *testing.T) {
ms := NewREST(registrytest.NewMinionRegistry([]string{"foo", "bar"}, api.NodeResources{}))
ctx := api.NewContext()
if obj, err := ms.Get(ctx, "foo"); err != nil || obj.(*api.Node).Name != "foo" {
t.Errorf("missing expected object")
}
if obj, err := ms.Get(ctx, "bar"); err != nil || obj.(*api.Node).Name != "bar" {
t.Errorf("missing expected object")
}
if _, err := ms.Get(ctx, "baz"); !errors.IsNotFound(err) {
t.Errorf("has unexpected error: %v", err)
}
obj, err := ms.Create(ctx, &api.Node{ObjectMeta: api.ObjectMeta{Name: "baz"}})
if err != nil {
t.Fatalf("insert failed: %v", err)
}
if !api.HasObjectMetaSystemFieldValues(&obj.(*api.Node).ObjectMeta) {
t.Errorf("storage did not populate object meta field values")
}
if m, ok := obj.(*api.Node); !ok || m.Name != "baz" {
t.Errorf("insert return value was weird: %#v", obj)
}
if obj, err := ms.Get(ctx, "baz"); err != nil || obj.(*api.Node).Name != "baz" {
t.Errorf("insert didn't actually insert")
}
obj, err = ms.Delete(ctx, "bar")
if err != nil {
t.Fatalf("delete failed")
}
if s, ok := obj.(*api.Status); !ok || s.Status != api.StatusSuccess {
t.Errorf("delete return value was weird: %#v", obj)
}
if _, err := ms.Get(ctx, "bar"); !errors.IsNotFound(err) {
t.Errorf("delete didn't actually delete: %v", err)
}
_, err = ms.Delete(ctx, "bar")
if err != ErrDoesNotExist {
t.Fatalf("delete returned wrong error")
}
list, err := ms.List(ctx, labels.Everything(), fields.Everything())
if err != nil {
t.Errorf("got error calling List")
}
expect := []api.Node{
{
ObjectMeta: api.ObjectMeta{Name: "foo"},
}, {
ObjectMeta: api.ObjectMeta{Name: "baz"},
},
}
nodeList := list.(*api.NodeList)
if len(expect) != len(nodeList.Items) || !contains(nodeList, "foo") || !contains(nodeList, "baz") {
t.Errorf("Unexpected list value: %#v", list)
}
}
示例5: Resolve
// Resolve will attempt to find an imagestream with a name that matches the passed in value
func (r ImageStreamResolver) Resolve(value string) (*ComponentMatch, error) {
ref, err := imageapi.ParseDockerImageReference(value)
if err != nil || len(ref.Registry) != 0 {
return nil, fmt.Errorf("image repositories must be of the form [<namespace>/]<name>[:<tag>|@<digest>]")
}
namespaces := r.Namespaces
if len(ref.Namespace) != 0 {
namespaces = []string{ref.Namespace}
}
searchTag := ref.Tag
if len(searchTag) == 0 {
searchTag = imageapi.DefaultImageTag
}
for _, namespace := range namespaces {
glog.V(4).Infof("checking ImageStream %s/%s with ref %q", namespace, ref.Name, searchTag)
repo, err := r.Client.ImageStreams(namespace).Get(ref.Name)
if err != nil {
if errors.IsNotFound(err) || errors.IsForbidden(err) {
continue
}
return nil, err
}
ref.Namespace = namespace
latest := imageapi.LatestTaggedImage(repo, searchTag)
if latest == nil {
// continue searching in the next namespace
glog.V(2).Infof("no image recorded for %s/%s:%s", repo.Namespace, repo.Name, searchTag)
continue
}
imageStreamImage, err := r.ImageStreamImages.ImageStreamImages(namespace).Get(ref.Name, latest.Image)
if err != nil {
if errors.IsNotFound(err) {
// continue searching in the next namespace
glog.V(2).Infof("tag %q is set, but image %q has been removed", searchTag, latest.Image)
continue
}
return nil, err
}
imageData := imageStreamImage.Image
ref.Registry = ""
return &ComponentMatch{
Value: ref.String(),
Argument: fmt.Sprintf("--image=%q", ref.String()),
Name: ref.Name,
Description: fmt.Sprintf("Image repository %s (tag %q) in project %s, tracks %q", repo.Name, searchTag, repo.Namespace, repo.Status.DockerImageRepository),
Builder: IsBuilderImage(&imageData.DockerImageMetadata),
Score: 0,
ImageStream: repo,
Image: &imageData.DockerImageMetadata,
ImageTag: searchTag,
}, nil
}
return nil, ErrNoMatch{value: value}
}
示例6: resolveImageStreamReference
// resolveImageStreamReference looks up the ImageStream[Tag/Image] and converts it to a
// docker pull spec that can be used in an Image field.
func (g *BuildGenerator) resolveImageStreamReference(ctx kapi.Context, from kapi.ObjectReference, defaultNamespace string) (string, error) {
var namespace string
if len(from.Namespace) != 0 {
namespace = from.Namespace
} else {
namespace = defaultNamespace
}
glog.V(4).Infof("Resolving ImageStreamReference %s of Kind %s in namespace %s", from.Name, from.Kind, namespace)
switch from.Kind {
case "ImageStream":
// NOTE: The 'ImageStream' reference should be used only for the 'output' image
is, err := g.Client.GetImageStream(kapi.WithNamespace(ctx, namespace), from.Name)
if err != nil {
glog.V(2).Infof("Error getting ImageStream %s/%s: %v", namespace, from.Name, err)
return "", err
}
image, err := imageapi.DockerImageReferenceForStream(is)
if err != nil {
glog.V(2).Infof("Error resolving Docker image reference for %s/%s: %v", namespace, from.Name, err)
return "", err
}
return image.String(), nil
case "ImageStreamImage":
imageStreamImage, err := g.Client.GetImageStreamImage(kapi.WithNamespace(ctx, namespace), from.Name)
if err != nil {
glog.V(2).Infof("Error ImageStreamReference %s in namespace %s: %v", from.Name, namespace, err)
if errors.IsNotFound(err) {
return "", err
}
return "", fatalError{err}
}
image := imageStreamImage.Image
glog.V(4).Infof("Resolved ImageStreamReference %s to image %s with reference %s in namespace %s", from.Name, image.Name, image.DockerImageReference, namespace)
return image.DockerImageReference, nil
case "ImageStreamTag":
imageStreamTag, err := g.Client.GetImageStreamTag(kapi.WithNamespace(ctx, namespace), from.Name)
if err != nil {
glog.V(2).Infof("Error resolving ImageStreamTag reference %s in namespace %s: %v", from.Name, namespace, err)
if errors.IsNotFound(err) {
return "", err
}
return "", fatalError{err}
}
image := imageStreamTag.Image
glog.V(4).Infof("Resolved ImageStreamTag %s to image %s with reference %s in namespace %s", from.Name, image.Name, image.DockerImageReference, namespace)
return image.DockerImageReference, nil
case "DockerImage":
return from.Name, nil
default:
return "", fatalError{fmt.Errorf("Unknown From Kind %s", from.Kind)}
}
}
示例7: getReferencedServiceAccountToken
func getReferencedServiceAccountToken(c *client.Client, ns string, name string, shouldWait bool) (string, string, error) {
tokenName := ""
token := ""
findToken := func() (bool, error) {
user, err := c.ServiceAccounts(ns).Get(name)
if errors.IsNotFound(err) {
return false, nil
}
if err != nil {
return false, err
}
for _, ref := range user.Secrets {
secret, err := c.Secrets(ns).Get(ref.Name)
if errors.IsNotFound(err) {
continue
}
if err != nil {
return false, err
}
if secret.Type != api.SecretTypeServiceAccountToken {
continue
}
name := secret.Annotations[api.ServiceAccountNameKey]
uid := secret.Annotations[api.ServiceAccountUIDKey]
tokenData := secret.Data[api.ServiceAccountTokenKey]
if name == user.Name && uid == string(user.UID) && len(tokenData) > 0 {
tokenName = secret.Name
token = string(tokenData)
return true, nil
}
}
return false, nil
}
if shouldWait {
err := wait.Poll(time.Second, 10*time.Second, findToken)
if err != nil {
return "", "", err
}
} else {
ok, err := findToken()
if err != nil {
return "", "", err
}
if !ok {
return "", "", fmt.Errorf("No token found for %s/%s", ns, name)
}
}
return tokenName, token, nil
}
示例8: syncNamespace
// syncNamespace makes namespace life-cycle decisions
func syncNamespace(kubeClient client.Interface, namespace api.Namespace) (err error) {
if namespace.DeletionTimestamp == nil {
return nil
}
// if there is a deletion timestamp, and the status is not terminating, then update status
if !namespace.DeletionTimestamp.IsZero() && namespace.Status.Phase != api.NamespaceTerminating {
newNamespace := api.Namespace{}
newNamespace.ObjectMeta = namespace.ObjectMeta
newNamespace.Status = namespace.Status
newNamespace.Status.Phase = api.NamespaceTerminating
result, err := kubeClient.Namespaces().Status(&newNamespace)
if err != nil {
return err
}
// work with the latest copy so we can proceed to clean up right away without another interval
namespace = *result
}
// if the namespace is already finalized, delete it
if finalized(namespace) {
err = kubeClient.Namespaces().Delete(namespace.Name)
if err != nil && !errors.IsNotFound(err) {
return err
}
return nil
}
// there may still be content for us to remove
err = deleteAllContent(kubeClient, namespace.Name)
if err != nil {
return err
}
// we have removed content, so mark it finalized by us
result, err := finalize(kubeClient, namespace)
if err != nil {
return err
}
// now check if all finalizers have reported that we delete now
if finalized(*result) {
err = kubeClient.Namespaces().Delete(namespace.Name)
if err != nil && !errors.IsNotFound(err) {
return err
}
}
return nil
}
示例9: makeDefaultErrorFunc
func (factory *ConfigFactory) makeDefaultErrorFunc(backoff *podBackoff, podQueue *cache.FIFO) func(pod *api.Pod, err error) {
return func(pod *api.Pod, err error) {
if err == scheduler.ErrNoNodesAvailable {
glog.V(4).Infof("Unable to schedule %v %v: no nodes are registered to the cluster; waiting", pod.Namespace, pod.Name)
} else {
glog.Errorf("Error scheduling %v %v: %v; retrying", pod.Namespace, pod.Name, err)
}
backoff.gc()
// Retry asynchronously.
// Note that this is extremely rudimentary and we need a more real error handling path.
go func() {
defer util.HandleCrash()
podID := pod.Name
podNamespace := pod.Namespace
backoff.wait(podID)
// Get the pod again; it may have changed/been scheduled already.
pod = &api.Pod{}
err := factory.Client.Get().Namespace(podNamespace).Resource("pods").Name(podID).Do().Into(pod)
if err != nil {
if !errors.IsNotFound(err) {
glog.Errorf("Error getting pod %v for retry: %v; abandoning", podID, err)
}
return
}
if pod.Spec.NodeName == "" {
podQueue.Add(pod)
}
}()
}
}
示例10: persistUpdate
func (s *ServiceController) persistUpdate(service *api.Service) error {
var err error
for i := 0; i < clientRetryCount; i++ {
_, err = s.kubeClient.Services(service.Namespace).Update(service)
if err == nil {
return nil
}
// If the object no longer exists, we don't want to recreate it. Just bail
// out so that we can process the delete, which we should soon be receiving
// if we haven't already.
if errors.IsNotFound(err) {
glog.Infof("Not persisting update to service that no longer exists: %v", err)
return nil
}
// TODO: Try to resolve the conflict if the change was unrelated to load
// balancers and public IPs. For now, just rely on the fact that we'll
// also process the update that caused the resource version to change.
if errors.IsConflict(err) {
glog.Infof("Not persisting update to service that has been changed since we received it: %v", err)
return nil
}
glog.Warningf("Failed to persist updated PublicIPs to service %s after creating its external load balancer: %v",
service.Name, err)
time.Sleep(clientRetryInterval)
}
return err
}
示例11: ensurePolicyBindingToMaster
// ensurePolicyBindingToMaster returns a PolicyBinding object that has a PolicyRef pointing to the Policy in the passed namespace.
func (m *VirtualStorage) ensurePolicyBindingToMaster(ctx kapi.Context, policyNamespace, policyBindingName string) (*authorizationapi.PolicyBinding, error) {
policyBinding, err := m.BindingRegistry.GetPolicyBinding(ctx, policyBindingName)
if err != nil {
if !kapierrors.IsNotFound(err) {
return nil, err
}
// if we have no policyBinding, go ahead and make one. creating one here collapses code paths below. We only take this hit once
policyBinding = policybindingregistry.NewEmptyPolicyBinding(kapi.NamespaceValue(ctx), policyNamespace, policyBindingName)
if err := m.BindingRegistry.CreatePolicyBinding(ctx, policyBinding); err != nil {
return nil, err
}
policyBinding, err = m.BindingRegistry.GetPolicyBinding(ctx, policyBindingName)
if err != nil {
return nil, err
}
}
if policyBinding.RoleBindings == nil {
policyBinding.RoleBindings = make(map[string]*authorizationapi.RoleBinding)
}
return policyBinding, nil
}
示例12: setEndpoints
// setEndpoints sets the endpoints for the given service.
// in a multi-master scenario only the master will be publishing an endpoint.
// see SchedulerServer.bootstrap.
func (m *SchedulerServer) setEndpoints(serviceName string, ip net.IP, port int) error {
// The setting we want to find.
want := []api.EndpointSubset{{
Addresses: []api.EndpointAddress{{IP: ip.String()}},
Ports: []api.EndpointPort{{Port: port, Protocol: api.ProtocolTCP}},
}}
ctx := api.NewDefaultContext()
e, err := m.client.Endpoints(api.NamespaceValue(ctx)).Get(serviceName)
createOrUpdate := m.client.Endpoints(api.NamespaceValue(ctx)).Update
if err != nil {
if errors.IsNotFound(err) {
createOrUpdate = m.client.Endpoints(api.NamespaceValue(ctx)).Create
}
e = &api.Endpoints{
ObjectMeta: api.ObjectMeta{
Name: serviceName,
Namespace: api.NamespaceDefault,
},
}
}
if !reflect.DeepEqual(e.Subsets, want) {
e.Subsets = want
glog.Infof("setting endpoints for master service %q to %#v", serviceName, e)
_, err = createOrUpdate(e)
return err
}
// We didn't make any changes, no need to actually call update.
return nil
}
示例13: EnsurePolicy
// EnsurePolicy returns the policy object for the specified namespace. If one does not exist, it is created for you. Permission to
// create, update, or delete roles in a namespace implies the ability to create a Policy object itself.
func (m *VirtualStorage) EnsurePolicy(ctx kapi.Context) (*authorizationapi.Policy, error) {
policy, err := m.PolicyStorage.GetPolicy(ctx, authorizationapi.PolicyName)
if err != nil {
if !kapierrors.IsNotFound(err) {
return nil, err
}
// if we have no policy, go ahead and make one. creating one here collapses code paths below. We only take this hit once
policy = NewEmptyPolicy(kapi.NamespaceValue(ctx))
if err := m.PolicyStorage.CreatePolicy(ctx, policy); err != nil {
return nil, err
}
policy, err = m.PolicyStorage.GetPolicy(ctx, authorizationapi.PolicyName)
if err != nil {
return nil, err
}
}
if policy.Roles == nil {
policy.Roles = make(map[string]*authorizationapi.Role)
}
return policy, nil
}
示例14: TestUpdateError
func TestUpdateError(t *testing.T) {
ctx := kapi.WithUser(kapi.WithNamespace(kapi.NewContext(), "unittest"), &user.DefaultInfo{Name: "system:admin"})
storage := makeTestStorage()
obj, err := storage.Create(ctx, &authorizationapi.RoleBinding{
ObjectMeta: kapi.ObjectMeta{Name: "my-different"},
RoleRef: kapi.ObjectReference{Name: "admin"},
})
if err != nil {
t.Errorf("unexpected error: %v", err)
return
}
original := obj.(*authorizationapi.RoleBinding)
roleBinding := &authorizationapi.RoleBinding{
ObjectMeta: kapi.ObjectMeta{Name: "my-roleBinding", ResourceVersion: original.ResourceVersion},
RoleRef: kapi.ObjectReference{Name: "admin"},
}
_, _, err = storage.Update(ctx, roleBinding)
if err == nil {
t.Errorf("Missing expected error")
return
}
if !kapierrors.IsNotFound(err) {
t.Errorf("Unexpected error %v", err)
}
}
示例15: TestGetEndpointsMissingService
func TestGetEndpointsMissingService(t *testing.T) {
registry := ®istrytest.ServiceRegistry{
Err: errors.NewNotFound("service", "foo"),
}
storage := NewREST(registry)
ctx := api.NewContext()
// returns service not found
_, err := storage.Get(ctx, "foo")
if !errors.IsNotFound(err) || !reflect.DeepEqual(err, errors.NewNotFound("service", "foo")) {
t.Errorf("expected NotFound error, got %#v", err)
}
// returns empty endpoints
registry.Err = nil
registry.Service = &api.Service{
ObjectMeta: api.ObjectMeta{Name: "foo"},
}
obj, err := storage.Get(ctx, "foo")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if obj.(*api.Endpoints).Endpoints != nil {
t.Errorf("unexpected endpoints: %#v", obj)
}
}