-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
206 lines (182 loc) · 4.76 KB
/
main.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
package main
import (
"errors"
"flag"
"fmt"
"os"
"strings"
"k8s.io/api/extensions/v1beta1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
_ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
)
const (
exitSuccess = 0
exitInvalidCmdArgs = 1
exitK8sOperationErr = 2
exitCanceled = 3
exitNeutral = 78
)
var (
ingressName string
ingressHost string
serviceName string
servicePort int
namespace string
pathRule string
skipConfirm bool
)
func usage() {
_, _ = fmt.Fprintf(flag.CommandLine.Output(), `Usage:
%s -ingress=<INGRESS_NAME> -host=<INGRESS_HOST> -service=<SERVICE_NAME> -port=<SERVICE_PORT> add
%s -ingress=<INGRESS_NAME> -host=<INGRESS_HOST> remove
Options:
`, os.Args[0], os.Args[0])
flag.PrintDefaults()
}
func main() {
flag.StringVar(&ingressName, "ingress", "", "name of kubernetes ingress (required).")
flag.StringVar(&ingressHost, "host", "", "ingress host (required).")
flag.StringVar(&pathRule, "path", "/*", "matching path rules of an incoming request (optional).")
flag.StringVar(&serviceName, "service", "", "name of kubernetes service (required when running 'add').")
flag.IntVar(&servicePort, "port", -1, "port number (required when running 'add').")
flag.StringVar(&namespace, "namespace", "", "kubernetes namespace (optional).")
flag.BoolVar(&skipConfirm, "y", false, "say yes in all confirmations")
flag.Usage = usage
flag.Parse()
op := flag.Arg(0)
err := validateCmdArgs(op)
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(exitInvalidCmdArgs)
}
status := run(op)
os.Exit(status)
}
func run(operation string) int {
client, err := initClient()
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, "error:", err)
return exitK8sOperationErr
}
ingress, err := client.ExtensionsV1beta1().Ingresses(namespace).Get(ingressName, metav1.GetOptions{})
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, "error:", err)
return exitK8sOperationErr
}
fmt.Println("before:")
prettyPrintRule(ingress)
switch operation {
case "add":
rule := createRule()
if added := addRule(ingress, rule); !added {
return exitSuccess
}
case "remove":
if found := removeRule(ingress); !found {
return exitSuccess
}
}
fmt.Println("after:")
prettyPrintRule(ingress)
if !confirm() {
return exitCanceled
}
_, err = client.ExtensionsV1beta1().Ingresses(namespace).Update(ingress)
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, "error:", err)
return exitK8sOperationErr
}
return exitSuccess
}
func validateCmdArgs(op string) error {
switch op {
case "add":
if ingressName == "" || ingressHost == "" || serviceName == "" || servicePort == -1 {
return errors.New("must specify 'ingress', 'host', 'service' and 'port' option")
}
case "remove":
if ingressName == "" || ingressHost == "" {
return errors.New("must specify 'ingress' and 'host'")
}
default:
return errors.New("command not found")
}
return nil
}
func initClient() (client *kubernetes.Clientset, err error) {
loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
loader := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
loadingRules,
&clientcmd.ConfigOverrides{},
)
config, err := loader.ClientConfig()
if err != nil {
return nil, err
}
if namespace == "" {
// Use namespace in context if it's empty.
namespace, _, err = loader.Namespace()
if err != nil {
return nil, err
}
}
return kubernetes.NewForConfig(config)
}
func createRule() v1beta1.IngressRule {
return v1beta1.IngressRule{
Host: ingressHost,
IngressRuleValue: v1beta1.IngressRuleValue{
HTTP: &v1beta1.HTTPIngressRuleValue{
Paths: []v1beta1.HTTPIngressPath{
{
Path: pathRule,
Backend: v1beta1.IngressBackend{
ServiceName: serviceName,
ServicePort: intstr.FromInt(servicePort),
},
},
},
},
},
}
}
func prettyPrintRule(ingress *v1beta1.Ingress) {
fmt.Println(ingress.Name)
for _, r := range ingress.Spec.Rules {
fmt.Printf("- %s\n", r.Host)
}
}
func confirm() bool {
if skipConfirm {
return true
}
fmt.Print("Apply? (y/N): ")
var response string
fmt.Scanln(&response)
if !strings.HasPrefix(strings.ToLower(response), "y") {
fmt.Println("canceled.")
return false
}
return true
}
func addRule(ingress *v1beta1.Ingress, rule v1beta1.IngressRule) (added bool) {
for _, r := range ingress.Spec.Rules {
if r.Host == rule.Host {
return false
}
}
ingress.Spec.Rules = append(ingress.Spec.Rules, rule)
return true
}
func removeRule(ingress *v1beta1.Ingress) (found bool) {
for i, r := range ingress.Spec.Rules {
if r.Host == ingressHost {
ingress.Spec.Rules = append(ingress.Spec.Rules[:i], ingress.Spec.Rules[i+1:]...)
return true
}
}
return false
}