util: NewK8sClient() should not panic on non-Kubernetes clusters

When NewK8sClient() detects and error, it used to call FatalLogMsg()
which causes a panic. There are additional features that can be used on
Kubernetes clusters, but these are not a requirement for most
functionalities of the driver.

Instead of causing a panic, returning an error should suffice. This
allows using the driver on non-Kubernetes clusters again.

Fixes: #2452
Signed-off-by: Niels de Vos <ndevos@redhat.com>
This commit is contained in:
Niels de Vos
2021-08-31 14:18:37 +02:00
committed by mergify[bot]
parent e8efa272a6
commit 60c2afbcca
9 changed files with 77 additions and 21 deletions

View File

@ -17,35 +17,34 @@ limitations under the License.
package k8s
import (
"fmt"
"os"
"github.com/ceph/ceph-csi/internal/util/log"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
)
// NewK8sClient create kubernetes client.
func NewK8sClient() *kubernetes.Clientset {
func NewK8sClient() (*kubernetes.Clientset, error) {
var cfg *rest.Config
var err error
cPath := os.Getenv("KUBERNETES_CONFIG_PATH")
if cPath != "" {
cfg, err = clientcmd.BuildConfigFromFlags("", cPath)
if err != nil {
log.FatalLogMsg("Failed to get cluster config with error: %v\n", err)
return nil, fmt.Errorf("failed to get cluster config from %q: %w", cPath, err)
}
} else {
cfg, err = rest.InClusterConfig()
if err != nil {
log.FatalLogMsg("Failed to get cluster config with error: %v\n", err)
return nil, fmt.Errorf("failed to get cluster config: %w", err)
}
}
client, err := kubernetes.NewForConfig(cfg)
if err != nil {
log.FatalLogMsg("Failed to create client with error: %v\n", err)
return nil, fmt.Errorf("failed to create client: %w", err)
}
return client
return client, nil
}

View File

@ -35,7 +35,12 @@ const (
)
func k8sGetNodeLabels(nodeName string) (map[string]string, error) {
client := k8s.NewK8sClient()
client, err := k8s.NewK8sClient()
if err != nil {
return nil, fmt.Errorf("can not get node %q information, failed "+
"to connect to Kubernetes: %w", nodeName, err)
}
node, err := client.CoreV1().Nodes().Get(context.TODO(), nodeName, metav1.GetOptions{})
if err != nil {
return nil, fmt.Errorf("failed to get node %q information: %w", nodeName, err)