Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🌱 Use errors package of Go #10875

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ func (r *KubeadmConfigReconciler) Reconcile(ctx context.Context, req ctrl.Reques
// Lookup the cluster the config owner is associated with
cluster, err := util.GetClusterByName(ctx, r.Client, configOwner.GetNamespace(), configOwner.ClusterName())
if err != nil {
if errors.Cause(err) == util.ErrNoCluster {
if errors.Is(errors.Cause(err), util.ErrNoCluster) {
log.Info(fmt.Sprintf("%s does not belong to a cluster yet, waiting until it's part of a cluster", configOwner.GetKind()))
return ctrl.Result{}, nil
}
Expand Down
3 changes: 2 additions & 1 deletion cmd/clusterctl/client/cluster/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,8 @@ func getGitHubClient(ctx context.Context, configVariablesClient config.Variables

// handleGithubErr wraps error messages.
func handleGithubErr(err error, message string, args ...interface{}) error {
if _, ok := err.(*github.RateLimitError); ok {
var rateLimitErr *github.RateLimitError
if errors.As(err, &rateLimitErr) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why not use errors.Is(....,, RateLimitError)?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same reason, thanks.

return errors.New("rate limit for github api has been reached. Please wait one hour or get a personal API token and assign it to the GITHUB_TOKEN environment variable")
}
return errors.Wrapf(err, message, args...)
Expand Down
17 changes: 11 additions & 6 deletions cmd/clusterctl/client/repository/repository_github.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ var (
retryableOperationTimeout = 1 * time.Minute
)

var rateLimitError *github.RateLimitError

// gitHubRepository provides support for providers hosted on GitHub.
//
// We support GitHub repositories that use the release feature to publish artifacts and versions.
Expand Down Expand Up @@ -319,7 +321,7 @@ func (g *gitHubRepository) getVersions(ctx context.Context) ([]string, error) {
if listReleasesErr != nil {
retryError = g.handleGithubErr(listReleasesErr, "failed to get the list of releases")
// Return immediately if we are rate limited.
if _, ok := listReleasesErr.(*github.RateLimitError); ok {
if errors.As(listReleasesErr, &rateLimitError) {
return false, retryError
}
return false, nil
Expand All @@ -334,7 +336,7 @@ func (g *gitHubRepository) getVersions(ctx context.Context) ([]string, error) {
if listReleasesErr != nil {
retryError = g.handleGithubErr(listReleasesErr, "failed to get the list of releases")
// Return immediately if we are rate limited.
if _, ok := listReleasesErr.(*github.RateLimitError); ok {
if errors.As(listReleasesErr, &rateLimitError) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why not use errors.Is(....,, RateLimitError)?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This code is originally type assertion, so errors.As is better than using errors.Is

return false, retryError
}
return false, nil
Expand Down Expand Up @@ -384,7 +386,7 @@ func (g *gitHubRepository) getReleaseByTag(ctx context.Context, tag string) (*gi
return false, retryError
}
// Return immediately if we are rate limited.
if _, ok := getReleasesErr.(*github.RateLimitError); ok {
if errors.As(getReleasesErr, &rateLimitError) {
return false, retryError
}
return false, nil
Expand Down Expand Up @@ -466,7 +468,7 @@ func (g *gitHubRepository) downloadFilesFromRelease(ctx context.Context, release
if downloadReleaseError != nil {
retryError = g.handleGithubErr(downloadReleaseError, "failed to download file %q from %q release", *release.TagName, fileName)
// Return immediately if we are rate limited.
if _, ok := downloadReleaseError.(*github.RateLimitError); ok {
if errors.As(downloadReleaseError, &rateLimitError) {
return false, retryError
}
return false, nil
Expand Down Expand Up @@ -499,10 +501,13 @@ func (g *gitHubRepository) downloadFilesFromRelease(ctx context.Context, release

// handleGithubErr wraps error messages.
func (g *gitHubRepository) handleGithubErr(err error, message string, args ...interface{}) error {
if _, ok := err.(*github.RateLimitError); ok {
if errors.As(err, &rateLimitError) {
return errors.New("rate limit for github api has been reached. Please wait one hour or get a personal API token and assign it to the GITHUB_TOKEN environment variable")
}
if ghErr, ok := err.(*github.ErrorResponse); ok {

var errorResponse *github.ErrorResponse
if errors.As(err, &errorResponse) {
ghErr := err.(*github.ErrorResponse)
if ghErr.Response.StatusCode == http.StatusNotFound {
return errNotFound
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@ func (r *ClusterResourceSetReconciler) ApplyClusterResourceSet(ctx context.Conte
for i, resource := range clusterResourceSet.Spec.Resources {
unstructuredObj, err := r.getResource(ctx, resource, cluster.GetNamespace())
if err != nil {
if err == ErrSecretTypeNotSupported {
if errors.Is(err, ErrSecretTypeNotSupported) {
conditions.MarkFalse(clusterResourceSet, addonsv1.ResourcesAppliedCondition, addonsv1.WrongSecretTypeReason, clusterv1.ConditionSeverityWarning, err.Error())
} else {
conditions.MarkFalse(clusterResourceSet, addonsv1.ResourcesAppliedCondition, addonsv1.RetrievingResourceFailedReason, clusterv1.ConditionSeverityWarning, err.Error())
Expand Down
2 changes: 1 addition & 1 deletion exp/internal/controllers/machinepool_controller_noderef.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ func (r *MachinePoolReconciler) reconcileNodeRefs(ctx context.Context, s *scope)
// Get the Node references.
nodeRefsResult, err := r.getNodeReferences(ctx, mp.Spec.ProviderIDList, mp.Spec.MinReadySeconds, s.nodeRefMap)
if err != nil {
if err == errNoAvailableNodes {
if errors.Is(err, errNoAvailableNodes) {
log.Info("Cannot assign NodeRefs to MachinePool, no matching Nodes")
// No need to requeue here. Nodes emit an event that triggers reconciliation.
return ctrl.Result{}, nil
Expand Down
2 changes: 1 addition & 1 deletion exp/internal/controllers/machinepool_controller_phases.go
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ func (r *MachinePoolReconciler) reconcileInfrastructure(ctx context.Context, s *
// Get and set Status.Replicas from the infrastructure provider.
err = util.UnstructuredUnmarshalField(infraConfig, &mp.Status.Replicas, "status", "replicas")
if err != nil {
if err != util.ErrUnstructuredFieldNotFound {
if !errors.Is(err, util.ErrUnstructuredFieldNotFound) {
return ctrl.Result{}, errors.Wrapf(err, "failed to retrieve replicas from infrastructure provider for MachinePool %q in namespace %q", mp.Name, mp.Namespace)
}
}
Expand Down
4 changes: 2 additions & 2 deletions internal/controllers/cluster/cluster_controller_phases.go
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ func (r *Reconciler) reconcileInfrastructure(ctx context.Context, s *scope) (ctr

// Get and parse Status.FailureDomains from the infrastructure provider.
failureDomains := clusterv1.FailureDomains{}
if err := util.UnstructuredUnmarshalField(s.infraCluster, &failureDomains, "status", "failureDomains"); err != nil && err != util.ErrUnstructuredFieldNotFound {
if err := util.UnstructuredUnmarshalField(s.infraCluster, &failureDomains, "status", "failureDomains"); err != nil && !errors.Is(err, util.ErrUnstructuredFieldNotFound) {
return ctrl.Result{}, errors.Wrapf(err, "failed to retrieve Status.FailureDomains from infrastructure provider for Cluster %q in namespace %q",
cluster.Name, cluster.Namespace)
}
Expand Down Expand Up @@ -346,7 +346,7 @@ func (r *Reconciler) reconcileKubeconfig(ctx context.Context, s *scope) (ctrl.Re
switch {
case apierrors.IsNotFound(err):
if err := kubeconfig.CreateSecret(ctx, r.Client, cluster); err != nil {
if err == kubeconfig.ErrDependentCertificateNotFound {
if errors.Is(err, kubeconfig.ErrDependentCertificateNotFound) {
log.Info("Could not find secret for cluster, requeuing", "Secret", secret.ClusterCA)
return ctrl.Result{RequeueAfter: 30 * time.Second}, nil
}
Expand Down
3 changes: 1 addition & 2 deletions internal/controllers/machine/machine_controller_noderef.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,12 +73,11 @@ func (r *Reconciler) reconcileNode(ctx context.Context, s *scope) (ctrl.Result,
// Even if Status.NodeRef exists, continue to do the following checks to make sure Node is healthy
node, err := r.getNode(ctx, remoteClient, *machine.Spec.ProviderID)
if err != nil {
if err == ErrNodeNotFound {
if errors.Is(err, ErrNodeNotFound) {
if !s.machine.DeletionTimestamp.IsZero() {
// Tolerate node not found when the machine is being deleted.
return ctrl.Result{}, nil
}

// While a NodeRef is set in the status, failing to get that node means the node is deleted.
// If Status.NodeRef is not set before, node still can be in the provisioning state.
if machine.Status.NodeRef != nil {
Expand Down
4 changes: 2 additions & 2 deletions internal/controllers/machine/machine_controller_phases.go
Original file line number Diff line number Diff line change
Expand Up @@ -275,15 +275,15 @@ func (r *Reconciler) reconcileInfrastructure(ctx context.Context, s *scope) (ctr

// Get and set Status.Addresses from the infrastructure provider.
err = util.UnstructuredUnmarshalField(s.infraMachine, &m.Status.Addresses, "status", "addresses")
if err != nil && err != util.ErrUnstructuredFieldNotFound {
if err != nil && !errors.Is(err, util.ErrUnstructuredFieldNotFound) {
return ctrl.Result{}, errors.Wrapf(err, "failed to retrieve addresses from infrastructure provider for Machine %q in namespace %q", m.Name, m.Namespace)
}

// Get and set the failure domain from the infrastructure provider.
var failureDomain string
err = util.UnstructuredUnmarshalField(s.infraMachine, &failureDomain, "spec", "failureDomain")
switch {
case err == util.ErrUnstructuredFieldNotFound: // no-op
case errors.Is(err, util.ErrUnstructuredFieldNotFound): // no-op
case err != nil:
return ctrl.Result{}, errors.Wrapf(err, "failed to retrieve failure domain from infrastructure provider for Machine %q in namespace %q", m.Name, m.Namespace)
default:
Expand Down
3 changes: 2 additions & 1 deletion internal/runtime/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,8 @@ func (c *client) CallExtension(ctx context.Context, hook runtimecatalog.Hook, fo
// If the error is errCallingExtensionHandler then apply failure policy to calculate
// the effective result of the operation.
ignore := *registration.FailurePolicy == runtimev1.FailurePolicyIgnore
if _, ok := err.(errCallingExtensionHandler); ok && ignore {
var errTyp errCallingExtensionHandler
if errors.As(err, &errTyp) && ignore {
// Update the response to a default success response and return.
log.Error(err, fmt.Sprintf("Ignoring error calling extension handler because of FailurePolicy %q", *registration.FailurePolicy))
response.SetStatus(runtimehooksv1.ResponseStatusSuccess)
Expand Down