-
Notifications
You must be signed in to change notification settings - Fork 22
/
client.go
84 lines (73 loc) · 2.07 KB
/
client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
//
//
// Copyright Red Hat
//
// 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/LICENSE-2.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.
package client
import (
"errors"
"fmt"
"os"
"os/exec"
"k8s.io/client-go/kubernetes"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/config"
)
type K8sClient struct {
kubeClient *kubernetes.Clientset
controllerClient client.Client
cli string
}
// NewK8sClient creates kubernetes client wrapper with helper functions and direct access to k8s go client
func NewK8sClient() (*K8sClient, error) {
cfg, err := config.GetConfig()
if err != nil {
return nil, err
}
kubeClient, err := kubernetes.NewForConfig(cfg)
if err != nil {
return nil, err
}
// Instantiate an instance of conroller-runtime client
controllerClient, err := client.New(config.GetConfigOrDie(), client.Options{})
if err != nil {
fmt.Println("failed to create client")
os.Exit(1)
}
h := &K8sClient{kubeClient: kubeClient, controllerClient: controllerClient}
h.cli, err = findCLI()
if err != nil {
fmt.Println("failed to find oc or kubectl cli")
os.Exit(1)
}
return h, nil
}
// Kube returns the clientset for Kubernetes upstream.
func (c *K8sClient) Kube() kubernetes.Interface {
return c.kubeClient
}
// findCLI returns the first found CLI compatible with oc/kubectl
func findCLI() (string, error) {
selected := os.Getenv("K8S_CLI")
if selected != "" {
return selected, nil
}
for _, cli := range []string{"oc", "kubectl"} {
_, err := exec.LookPath(cli)
if err != nil {
continue
}
return cli, nil
}
return "", errors.New("no oc/kubectl CLI found")
}