-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdeployment.go
87 lines (80 loc) · 2.63 KB
/
deployment.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
85
86
87
package cmd
import (
"context"
"fmt"
"path/filepath"
"github.com/altinn/dotnet-monitor-sidecar-cli/pkg/errors"
dmskube "github.com/altinn/dotnet-monitor-sidecar-cli/pkg/kubernetes"
"github.com/altinn/dotnet-monitor-sidecar-cli/pkg/utils"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/util/homedir"
)
// AddToDeployment adds a debug sidecar to a deployment and configures it
func AddToDeployment(ctx context.Context, kubeconfig string, namespace string, deploymentname, containername, debugimage string) {
if home := homedir.HomeDir(); home != "" && kubeconfig == "" {
kubeconfig = filepath.Join(home, ".kube", "config")
}
config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
panic(err.Error())
}
if namespace == "" {
namespace, err = utils.GetNamespaceFromCurrentContext()
if err != nil {
fmt.Printf("Error getting namespace: %v", err)
return
}
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
h := dmskube.Helper{
Client: clientset,
}
d, token, err := h.AddDebugSidecarDeployment(ctx, namespace, deploymentname, containername, debugimage)
if err != nil {
if errors.IsAlreadyPresent(err) {
fmt.Printf("Debug sidecar already attached to deployment %s\n", d.Name)
return
}
fmt.Printf("Failed to attach sidecar to deployment %s: %v\n", deploymentname, err)
return
}
fmt.Printf("Added sidecar to deployment %s with uid %s\n", d.Name, d.UID)
fmt.Printf("Portforward to one of the pods with dmsctl port-forward [podname].\nQuery the API with this auth header:\nAuthorization: Bearer %s\n", token)
}
// RemoveFromDeployment removes the debug sidecar and configuration from a deployment
func RemoveFromDeployment(ctx context.Context, kubeconfig string, namespace string, deploymentname string) {
if home := homedir.HomeDir(); home != "" && kubeconfig == "" {
kubeconfig = filepath.Join(home, ".kube", "config")
}
config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
panic(err.Error())
}
if namespace == "" {
namespace, err = utils.GetNamespaceFromCurrentContext()
if err != nil {
fmt.Printf("Error getting namespace: %v", err)
return
}
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
h := dmskube.Helper{
Client: clientset,
}
d, err := h.RemoveDebugSidecarDeployment(ctx, namespace, deploymentname)
if err != nil {
if errors.IsNotPresent(err) {
fmt.Printf("Debug sidecar not attached to deployment %s\n", d.Name)
return
}
panic(err.Error())
}
fmt.Printf("Removed sidecar from deployment %s with uid %s\n", d.Name, d.UID)
}