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 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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 @@ -183,7 +183,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
Copy link
Member

Choose a reason for hiding this comment

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

can be a local var in getVersions()?

Copy link
Member Author

Choose a reason for hiding this comment

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

rateLimitError is used in many func of repository package. So I think it's better to prevent omission of change.


// 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 @@ -385,7 +387,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 @@ -467,7 +469,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 @@ -500,10 +502,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 _, 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 @@ -84,7 +84,7 @@ func (r *MachinePoolReconciler) reconcileNodeRefs(ctx context.Context, cluster *
// Get the Node references.
nodeRefsResult, err := r.getNodeReferences(ctx, clusterClient, mp.Spec.ProviderIDList)
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 @@ -301,7 +301,7 @@ func (r *MachinePoolReconciler) reconcileInfrastructure(ctx context.Context, clu
// 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 @@ -207,7 +207,7 @@ func (r *Reconciler) reconcileInfrastructure(ctx context.Context, cluster *clust

// Get and parse Status.FailureDomains from the infrastructure provider.
failureDomains := clusterv1.FailureDomains{}
if err := util.UnstructuredUnmarshalField(infraConfig, &failureDomains, "status", "failureDomains"); err != nil && err != util.ErrUnstructuredFieldNotFound {
if err := util.UnstructuredUnmarshalField(infraConfig, &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 @@ -295,7 +295,7 @@ func (r *Reconciler) reconcileKubeconfig(ctx context.Context, cluster *clusterv1
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
18 changes: 16 additions & 2 deletions internal/controllers/machine/machine_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -341,14 +341,28 @@ type scope struct {
bootstrapConfig *unstructured.Unstructured
}

func is(err error) bool {
errs := []error{
errNoControlPlaneNodes, errLastControlPlaneNode,
errNilNodeRef, errClusterIsBeingDeleted,
errControlPlaneIsBeingDeleted,
}
for _, e := range errs {
if errors.Is(err, e) {
return true
}
}
return false
}

func (r *Reconciler) reconcileDelete(ctx context.Context, cluster *clusterv1.Cluster, m *clusterv1.Machine) (ctrl.Result, error) { //nolint:gocyclo
log := ctrl.LoggerFrom(ctx)

err := r.isDeleteNodeAllowed(ctx, cluster, m)
isDeleteNodeAllowed := err == nil
if err != nil {
switch err {
case errNoControlPlaneNodes, errLastControlPlaneNode, errNilNodeRef, errClusterIsBeingDeleted, errControlPlaneIsBeingDeleted:
switch {
case is(err):
Copy link
Member

Choose a reason for hiding this comment

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

isKnownError or something more descriptive, also you can inline the function inside reconcileDelete

nodeName := ""
if m.Status.NodeRef != nil {
nodeName = m.Status.NodeRef.Name
Expand Down
2 changes: 1 addition & 1 deletion internal/controllers/machine/machine_controller_noderef.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ 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) {
// 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 @@ -317,15 +317,15 @@ func (r *Reconciler) reconcileInfrastructure(ctx context.Context, s *scope) (ctr

// Get and set Status.Addresses from the infrastructure provider.
err = util.UnstructuredUnmarshalField(infraConfig, &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(infraConfig, &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.Info(fmt.Sprintf("ignoring error calling extension handler because of FailurePolicy %q", *registration.FailurePolicy))
response.SetStatus(runtimehooksv1.ResponseStatusSuccess)
Expand Down
Loading