Skip to content

Commit

Permalink
Some more error wrapping
Browse files Browse the repository at this point in the history
  • Loading branch information
marccampbell committed Jul 31, 2019
1 parent f7109f3 commit e6416d7
Show file tree
Hide file tree
Showing 7 changed files with 74 additions and 45 deletions.
5 changes: 3 additions & 2 deletions cmd/preflight/cli/interactive_results.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (

ui "github.com/gizak/termui/v3"
"github.com/gizak/termui/v3/widgets"
"github.com/pkg/errors"
analyzerunner "github.com/replicatedhq/troubleshoot/pkg/analyze"
)

Expand All @@ -20,7 +21,7 @@ var (

func showInteractiveResults(preflightName string, analyzeResults []*analyzerunner.AnalyzeResult) error {
if err := ui.Init(); err != nil {
return err
return errors.Wrap(err, "failed to create terminal ui")
}
defer ui.Close()

Expand Down Expand Up @@ -244,7 +245,7 @@ func save(preflightName string, analyzeResults []*analyzerunner.AnalyzeResult) (
}

if err := ioutil.WriteFile(filename, []byte(results), 0644); err != nil {
return "", err
return "", errors.Wrap(err, "failed to save preflight results")
}

return filename, nil
Expand Down
22 changes: 18 additions & 4 deletions cmd/preflight/cli/run_nocrd.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"strings"
"time"

"github.com/pkg/errors"
analyzerunner "github.com/replicatedhq/troubleshoot/pkg/analyze"
troubleshootv1beta1 "github.com/replicatedhq/troubleshoot/pkg/apis/troubleshoot/v1beta1"
collectrunner "github.com/replicatedhq/troubleshoot/pkg/collect"
Expand All @@ -22,10 +23,12 @@ import (
"github.com/tj/go-spin"
"gopkg.in/yaml.v2"
corev1 "k8s.io/api/core/v1"
kuberneteserrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
types "k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/cache"
"sigs.k8s.io/controller-runtime/pkg/client"
Expand Down Expand Up @@ -76,6 +79,7 @@ func runPreflightsNoCRD(v *viper.Viper, arg string) error {
for {
select {
case <-finishedCh:
fmt.Printf("\r")
return
case <-time.After(time.Millisecond * 100):
fmt.Printf("\r \033[36mRunning Preflight checks\033[m %s ", s.Next())
Expand Down Expand Up @@ -162,10 +166,20 @@ func runCollectors(v *viper.Viper, preflight troubleshootv1beta1.Preflight) (map
}

// deploy an object that "owns" everything to aid in cleanup
configMapNamespacedName := types.NamespacedName{
Name: fmt.Sprintf("preflight-%s-owner", preflight.Name),
Namespace: v.GetString("namespace"),
}

foundConfigMap := &corev1.ConfigMap{}
err = client.Get(context.Background(), configMapNamespacedName, foundConfigMap)
if err == nil || !kuberneteserrors.IsNotFound(err) {
return nil, errors.Wrap(err, "failed to get existing config map")
}
owner := corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: fmt.Sprintf("preflight-%s-owner", preflight.Name),
Namespace: v.GetString("namespace"),
Name: configMapNamespacedName.Name,
Namespace: configMapNamespacedName.Namespace,
},
TypeMeta: metav1.TypeMeta{
APIVersion: "v1",
Expand All @@ -174,7 +188,7 @@ func runCollectors(v *viper.Viper, preflight troubleshootv1beta1.Preflight) (map
Data: make(map[string]string),
}
if err := client.Create(context.Background(), &owner); err != nil {
return nil, err
return nil, errors.Wrap(err, "failed to create config map")
}
defer func() {
if err := client.Delete(context.Background(), &owner); err != nil {
Expand Down Expand Up @@ -272,7 +286,7 @@ func runCollectors(v *viper.Viper, preflight troubleshootv1beta1.Preflight) (map
for _, collector := range desiredCollectors {
_, pod, err := collectrunner.CreateCollector(client, s, &owner, preflight.Name, v.GetString("namespace"), serviceAccountName, "preflight", collector, v.GetString("image"), v.GetString("pullpolicy"))
if err != nil {
return nil, err
return nil, errors.Wrap(err, "failed to create collector")
}
podsCreated = append(podsCreated, pod)
}
Expand Down
45 changes: 33 additions & 12 deletions cmd/preflight/cli/serviceaccount.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ package cli
import (
"fmt"

"github.com/pkg/errors"
troubleshootv1beta1 "github.com/replicatedhq/troubleshoot/pkg/apis/troubleshoot/v1beta1"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
kuberneteserrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
)
Expand All @@ -31,9 +33,16 @@ func createServiceAccount(preflight troubleshootv1beta1.Preflight, namespace str
},
},
}
_, err := clientset.CoreV1().ServiceAccounts(namespace).Create(&serviceAccount)
if err != nil {
return "", err

_, err := clientset.CoreV1().ServiceAccounts(namespace).Get(serviceAccount.Name, metav1.GetOptions{})
if err != nil && !kuberneteserrors.IsNotFound(err) {
return "", errors.Wrap(err, "failed to get existing service account")
}
if kuberneteserrors.IsNotFound(err) {
_, err := clientset.CoreV1().ServiceAccounts(namespace).Create(&serviceAccount)
if err != nil {
return "", errors.Wrap(err, "failed to create service account")
}
}

role := rbacv1.ClusterRole{
Expand Down Expand Up @@ -78,9 +87,15 @@ func createServiceAccount(preflight troubleshootv1beta1.Preflight, namespace str
},
},
}
_, err = clientset.RbacV1().ClusterRoles().Create(&role)
if err != nil {
return "", err
_, err = clientset.RbacV1().ClusterRoles().Get(role.Name, metav1.GetOptions{})
if err != nil && !kuberneteserrors.IsNotFound(err) {
return "", errors.Wrap(err, "failed to get eisting cluster role")
}
if kuberneteserrors.IsNotFound(err) {
_, err = clientset.RbacV1().ClusterRoles().Create(&role)
if err != nil {
return "", errors.Wrap(err, "failed to create cluster role")
}
}

roleBinding := rbacv1.ClusterRoleBinding{
Expand All @@ -105,25 +120,31 @@ func createServiceAccount(preflight troubleshootv1beta1.Preflight, namespace str
Name: name,
},
}
_, err = clientset.RbacV1().ClusterRoleBindings().Create(&roleBinding)
if err != nil {
return "", err
_, err = clientset.RbacV1().ClusterRoleBindings().Get(roleBinding.Name, metav1.GetOptions{})
if err != nil && !kuberneteserrors.IsNotFound(err) {
return "", errors.Wrap(err, "failed to get existing cluster role binding")
}
if kuberneteserrors.IsNotFound(err) {
_, err = clientset.RbacV1().ClusterRoleBindings().Create(&roleBinding)
if err != nil {
return "", errors.Wrap(err, "failed to create cluster role binding")
}
}

return name, nil
}

func removeServiceAccount(name string, namespace string, clientset *kubernetes.Clientset) error {
if err := clientset.RbacV1().ClusterRoleBindings().Delete(name, &metav1.DeleteOptions{}); err != nil {
return err
return errors.Wrap(err, "failed to delete cluster role binding")
}

if err := clientset.RbacV1().ClusterRoles().Delete(name, &metav1.DeleteOptions{}); err != nil {
return err
return errors.Wrap(err, "failed to delete cluster role")
}

if err := clientset.CoreV1().ServiceAccounts(namespace).Delete(name, &metav1.DeleteOptions{}); err != nil {
return err
return errors.Wrap(err, "failed to delete service account")
}

return nil
Expand Down
28 changes: 11 additions & 17 deletions examples/preflight/sample-preflight.yaml
Original file line number Diff line number Diff line change
@@ -1,41 +1,35 @@
apiVersion: troubleshoot.replicated.com/v1beta1
kind: Preflight
metadata:
name: check-kubernetes-version
name: example-preflight-checks
spec:
analyzers:
- clusterVersion:
outcomes:
- fail:
when: "< 1.14.0"
message: The application requires at Kubernetes 1.14.0 or later, and recommends 1.15.0.
when: "< 1.13.0"
message: The application requires at Kubernetes 1.13.0 or later, and recommends 1.15.0.
uri: https://www.kubernetes.io
- warn:
when: "< 1.15.0"
message: Your cluster meets the minimum version of Kubernetes, but we recommend you update to 1.15.0 or later.
uri: https://kubernetes.io
- pass:
message: Your cluster meets the recommended and required versions of Kubernetes.
- customResourceDefinitionName:
customResourceDefinitionName: rook
- customResourceDefinition:
customResourceDefinitionName: constrainttemplates.templates.gatekeeper.sh
checkName: Gatekeeper policy runtime is installed
outcomes:
- fail:
message: Rook is required for the application. Rook was not found in the cluster.
message: Gatekeeper is required for the application, but not found in the cluster.
- pass:
message: Found a supported version of Rook installed and running in the cluster.
message: Found a supported version of Gatekeeper installed and running in the cluster.
- imagePullSecret:
checkName: Registry credneitlas for Quay.io
checkName: Registry credentials for Quay.io
registryName: quay.io
outcomes:
- fail:
message: Cannot pull from quay.io
message: |
Cannot pull from quay.io. An image pull secret should be deployed to the cluster that has credentials to pull the images. To obtain this secret, please contact your support rep.
- pass:
message: Found credentials to pull from quay.io
- storageClass:
checkName: Required storage classes
storageClassName: "expected-storage-class-name"
outcomes:
- fail:
message: The required storage class was not found in the cluster.
- pass:
message: The required storage class was found in the cluster.
3 changes: 1 addition & 2 deletions pkg/analyze/analyzer.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
package analyzer

import (
"errors"

"github.com/pkg/errors"
troubleshootv1beta1 "github.com/replicatedhq/troubleshoot/pkg/apis/troubleshoot/v1beta1"
)

Expand Down
11 changes: 5 additions & 6 deletions pkg/analyze/cluster_version.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,28 @@ package analyzer

import (
"encoding/json"
"errors"
"strings"

"github.com/blang/semver"
"github.com/pkg/errors"
troubleshootv1beta1 "github.com/replicatedhq/troubleshoot/pkg/apis/troubleshoot/v1beta1"
"github.com/replicatedhq/troubleshoot/pkg/collect"
)

func analyzeClusterVersion(analyzer *troubleshootv1beta1.ClusterVersion, getCollectedFileContents func(string) ([]byte, error)) (*AnalyzeResult, error) {
// TODO: ++++++++
clusterInfo, err := getCollectedFileContents("cluster-info/cluster_version.json")
if err != nil {
return nil, err
return nil, errors.Wrap(err, "failed top get contents of cluster_version.json")
}

collectorClusterVersion := collect.ClusterVersion{}
if err := json.Unmarshal(clusterInfo, &collectorClusterVersion); err != nil {
return nil, err
return nil, errors.Wrap(err, "failed to parse cluster_version.json")
}

k8sVersion, err := semver.Make(strings.TrimLeft(collectorClusterVersion.String, "v"))
if err != nil {
return nil, err
return nil, errors.Wrap(err, "failed to parse semver from cluster_version.json")
}

result := AnalyzeResult{}
Expand Down Expand Up @@ -63,7 +62,7 @@ func analyzeClusterVersion(analyzer *troubleshootv1beta1.ClusterVersion, getColl

whenRange, err := semver.ParseRange(when)
if err != nil {
return nil, err
return nil, errors.Wrap(err, "failed to parse semver range")
}

if whenRange(k8sVersion) {
Expand Down
5 changes: 3 additions & 2 deletions pkg/analyze/image_pull_secret.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@ package analyzer
import (
"encoding/json"

"github.com/pkg/errors"
troubleshootv1beta1 "github.com/replicatedhq/troubleshoot/pkg/apis/troubleshoot/v1beta1"
)

func analyzeImagePullSecret(analyzer *troubleshootv1beta1.ImagePullSecret, getChildCollectedFileContents func(string) (map[string][]byte, error)) (*AnalyzeResult, error) {
imagePullSecrets, err := getChildCollectedFileContents("cluster-resources/image-pull-secrets")
if err != nil {
return nil, err
return nil, errors.Wrap(err, "failed to get file contents for image pull secrets")
}

var failOutcome *troubleshootv1beta1.Outcome
Expand All @@ -32,7 +33,7 @@ func analyzeImagePullSecret(analyzer *troubleshootv1beta1.ImagePullSecret, getCh
for _, v := range imagePullSecrets {
registryAndUsername := make(map[string]string)
if err := json.Unmarshal(v, &registryAndUsername); err != nil {
return nil, err
return nil, errors.Wrap(err, "failed to parse registry secret")
}

for registry, _ := range registryAndUsername {
Expand Down

0 comments on commit e6416d7

Please sign in to comment.