-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoptions.go
109 lines (93 loc) · 2.42 KB
/
options.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package internal
import (
"context"
"fmt"
flag "github.com/spf13/pflag"
networkv1 "k8s.io/api/networking/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/json"
kube "k8s.io/cli-runtime/pkg/genericclioptions"
)
type ToggleOptions struct {
Service string
Ingress string
Kube *kube.ConfigFlags
Host *string
}
type Patch struct {
Operation string `json:"op"`
Path string `json:"path"`
Value interface{} `json:"value,omitempty"`
}
func (opts *ToggleOptions) Parse() *flag.FlagSet {
fs := flag.NewFlagSet("options", flag.ExitOnError)
opts.Kube = &kube.ConfigFlags{
KubeConfig: stringptr(""),
ClusterName: stringptr(""),
Context: stringptr(""),
Namespace: stringptr(""),
}
namespace, _, err := opts.Kube.ToRawKubeConfigLoader().Namespace()
if err == nil {
opts.Kube.Namespace = stringptr(namespace)
}
var host string
fs.StringVar(&host, "host", "", "Domain name")
opts.Kube.AddFlags(fs)
opts.Host = &host
return fs
}
func (opts *ToggleOptions) Patch(patch *Patch) error {
k8s, err := NewClient(opts.Kube)
if err != nil {
return err
}
body, err := encode(patch)
if err != nil {
return err
}
options := metav1.PatchOptions{
FieldManager: "kubectl-patch",
}
if opts.Service != "" {
svc, err := k8s.
CoreV1().
Services(*opts.Kube.Namespace).
Patch(context.Background(), opts.Service, types.JSONPatchType, body, options)
if err == nil {
fmt.Printf("Service %s/%s has been patched\n", svc.Namespace, svc.Name)
}
} else if opts.Ingress != "" {
ingress, err := k8s.
NetworkingV1().
Ingresses(*opts.Kube.Namespace).
Patch(context.Background(), opts.Ingress, types.JSONPatchType, body, options)
if err == nil {
fmt.Printf("Ingress %s/%s has been patched\n", ingress.Namespace, ingress.Name)
}
}
return err
}
func encode(patch *Patch) ([]byte, error) {
data := [1]Patch{*patch}
return json.Marshal(data)
}
func stringptr(s string) *string {
return &s
}
func (opts *ToggleOptions) GetIngress(resource string) (*networkv1.Ingress, error) {
k8s, err := NewClient(opts.Kube)
if err != nil {
return nil, err
}
options := metav1.GetOptions{}
ingress, err := k8s.
NetworkingV1().
Ingresses(*opts.Kube.Namespace).
Get(context.Background(), resource, options)
if err == nil {
fmt.Printf("Ingress %s/%s has been patched\n", ingress.Namespace, ingress.Name)
}
return ingress, nil
}