2020-07-10 10:44:59 +00:00
|
|
|
/*
|
|
|
|
Copyright 2020 The CephCSI Authors.
|
|
|
|
|
|
|
|
Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
you may not use this file except in compliance with the License.
|
|
|
|
You may obtain a copy of the License at
|
|
|
|
|
|
|
|
http://www.apache.org/licenses/LICENSE2.0
|
|
|
|
|
|
|
|
Unless required by applicable law or agreed to in writing, software
|
|
|
|
distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
See the License for the specific language governing permissions and
|
|
|
|
limitations under the License.
|
|
|
|
*/
|
|
|
|
|
2021-08-26 11:15:47 +00:00
|
|
|
package k8s
|
2020-07-10 10:44:59 +00:00
|
|
|
|
|
|
|
import (
|
2021-08-31 12:18:37 +00:00
|
|
|
"fmt"
|
2020-07-10 10:44:59 +00:00
|
|
|
"os"
|
|
|
|
|
2021-08-26 11:15:47 +00:00
|
|
|
"k8s.io/client-go/kubernetes"
|
2020-07-10 10:44:59 +00:00
|
|
|
"k8s.io/client-go/rest"
|
|
|
|
"k8s.io/client-go/tools/clientcmd"
|
|
|
|
)
|
|
|
|
|
2023-10-30 08:20:30 +00:00
|
|
|
var kubeclient *kubernetes.Clientset
|
|
|
|
|
2020-07-19 12:21:03 +00:00
|
|
|
// NewK8sClient create kubernetes client.
|
2021-08-31 12:18:37 +00:00
|
|
|
func NewK8sClient() (*kubernetes.Clientset, error) {
|
2023-10-30 08:20:30 +00:00
|
|
|
if kubeclient != nil {
|
|
|
|
return kubeclient, nil
|
|
|
|
}
|
|
|
|
|
2020-07-10 10:44:59 +00:00
|
|
|
var cfg *rest.Config
|
|
|
|
var err error
|
|
|
|
cPath := os.Getenv("KUBERNETES_CONFIG_PATH")
|
|
|
|
if cPath != "" {
|
|
|
|
cfg, err = clientcmd.BuildConfigFromFlags("", cPath)
|
|
|
|
if err != nil {
|
2021-08-31 12:18:37 +00:00
|
|
|
return nil, fmt.Errorf("failed to get cluster config from %q: %w", cPath, err)
|
2020-07-10 10:44:59 +00:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
cfg, err = rest.InClusterConfig()
|
|
|
|
if err != nil {
|
2021-08-31 12:18:37 +00:00
|
|
|
return nil, fmt.Errorf("failed to get cluster config: %w", err)
|
2020-07-10 10:44:59 +00:00
|
|
|
}
|
|
|
|
}
|
2021-08-26 11:15:47 +00:00
|
|
|
client, err := kubernetes.NewForConfig(cfg)
|
2020-07-10 10:44:59 +00:00
|
|
|
if err != nil {
|
2021-08-31 12:18:37 +00:00
|
|
|
return nil, fmt.Errorf("failed to create client: %w", err)
|
2020-07-10 10:44:59 +00:00
|
|
|
}
|
2021-07-22 05:45:17 +00:00
|
|
|
|
2023-10-30 08:20:30 +00:00
|
|
|
kubeclient = client
|
|
|
|
|
2021-08-31 12:18:37 +00:00
|
|
|
return client, nil
|
2020-07-10 10:44:59 +00:00
|
|
|
}
|
2023-11-02 06:00:08 +00:00
|
|
|
|
|
|
|
// RunsOnKubernetes checks if the application is running within a Kubernetes cluster
|
|
|
|
// by inspecting the presence of the KUBERNETES_SERVICE_HOST environment variable.
|
|
|
|
func RunsOnKubernetes() bool {
|
|
|
|
kubernetesServiceHost := os.Getenv("KUBERNETES_SERVICE_HOST")
|
|
|
|
|
|
|
|
return kubernetesServiceHost != ""
|
|
|
|
}
|