/
k8sInit.go
49 lines (41 loc) · 1.33 KB
/
k8sInit.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
// Copyright 2020 IBM Corp.
// SPDX-License-Identifier: Apache-2.0
package datauser
import (
"os"
"strings"
"emperror.dev/errors"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
kclient "sigs.k8s.io/controller-runtime/pkg/client"
kconfig "sigs.k8s.io/controller-runtime/pkg/client/config"
app "fybrik.io/fybrik/manager/apis/app/v1beta1"
)
const (
currentNamespacePath = "/var/run/secrets/kubernetes.io/serviceaccount/namespace"
)
// K8sClient contains the contextual info about the REST client for k8s
type K8sClient struct {
client kclient.Client
namespace string
}
// GetCurrentNamespace returns the namespace in which the REST api service is deployed - which should be a user namespace
func GetCurrentNamespace() string {
if data, err := os.ReadFile(currentNamespacePath); err == nil {
if ns := strings.TrimSpace(string(data)); len(ns) > 0 {
return ns
}
}
return "default"
}
// K8sInit initializes a client to communicate with kubernetes
func K8sInit() (*K8sClient, error) {
newScheme := runtime.NewScheme()
_ = app.AddToScheme(newScheme)
_ = v1.AddToScheme(newScheme)
client, err := kclient.New(kconfig.GetConfigOrDie(), kclient.Options{Scheme: newScheme})
if err != nil {
return nil, errors.Wrap(err, "failed to create client")
}
return &K8sClient{client: client, namespace: GetCurrentNamespace()}, nil
}