forked from kubernetes-sigs/ingress2gateway
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprint.go
More file actions
297 lines (251 loc) · 10.4 KB
/
print.go
File metadata and controls
297 lines (251 loc) · 10.4 KB
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
/*
Copyright 2023 The Kubernetes Authors.
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 cmd
import (
"fmt"
"log"
"os"
"strings"
"github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw"
"github.com/samber/lo"
"github.com/spf13/cobra"
"k8s.io/cli-runtime/pkg/genericclioptions"
"k8s.io/cli-runtime/pkg/printers"
"k8s.io/client-go/tools/clientcmd"
// Call init function for the providers
_ "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/providers/apisix"
_ "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/providers/ingressnginx"
_ "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/providers/istio"
_ "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/providers/kong"
_ "github.com/kubernetes-sigs/ingress2gateway/pkg/i2gw/providers/openapi3"
)
type PrintRunner struct {
// outputFormat contains currently set output format. Value assigned via --output/-o flag.
// Defaults to YAML.
outputFormat string
// The path to the input yaml config file. Value assigned via --input-file flag
inputFile string
// The namespace used to query Gateway API objects. Value assigned via
// --namespace/-n flag.
// On absence, the current user active namespace is used.
namespace string
// allNamespaces indicates whether all namespaces should be used. Value assigned via
// --all-namespaces/-A flag.
allNamespaces bool
// resourcePrinter determines how resource objects are printed out
resourcePrinter printers.ResourcePrinter
// Only resources that matches this filter will be processed.
namespaceFilter string
// providers indicates which providers are used to execute convert action.
providers []string
// Provider specific flags --<provider>-<flag>.
providerSpecificFlags map[string]*string
}
// PrintGatewayAPIObjects performs necessary steps to digest and print
// converted Gateway API objects. The steps include reading from the source,
// construct ingresses and provider-specific resources, convert them, then print
// the Gateway API objects out.
func (pr *PrintRunner) PrintGatewayAPIObjects(cmd *cobra.Command, _ []string) error {
err := pr.initializeResourcePrinter()
if err != nil {
return fmt.Errorf("failed to initialize resrouce printer: %w", err)
}
err = pr.initializeNamespaceFilter()
if err != nil {
return fmt.Errorf("failed to initialize namespace filter: %w", err)
}
gatewayResources, err := i2gw.ToGatewayAPIResources(cmd.Context(), pr.namespaceFilter, pr.inputFile, pr.providers, pr.getProviderSpecificFlags())
if err != nil {
return err
}
pr.outputResult(gatewayResources)
return nil
}
func (pr *PrintRunner) outputResult(gatewayResources []i2gw.GatewayResources) {
resourceCount := 0
for _, r := range gatewayResources {
resourceCount += len(r.GatewayClasses)
for _, gatewayClass := range r.GatewayClasses {
gatewayClass := gatewayClass
err := pr.resourcePrinter.PrintObj(&gatewayClass, os.Stdout)
if err != nil {
fmt.Printf("# Error printing %s GatewayClass: %v\n", gatewayClass.Name, err)
}
}
}
for _, r := range gatewayResources {
resourceCount += len(r.Gateways)
for _, gateway := range r.Gateways {
gateway := gateway
err := pr.resourcePrinter.PrintObj(&gateway, os.Stdout)
if err != nil {
fmt.Printf("# Error printing %s Gateway: %v\n", gateway.Name, err)
}
}
}
for _, r := range gatewayResources {
resourceCount += len(r.HTTPRoutes)
for _, httpRoute := range r.HTTPRoutes {
httpRoute := httpRoute
err := pr.resourcePrinter.PrintObj(&httpRoute, os.Stdout)
if err != nil {
fmt.Printf("# Error printing %s HTTPRoute: %v\n", httpRoute.Name, err)
}
}
}
for _, r := range gatewayResources {
resourceCount += len(r.TLSRoutes)
for _, tlsRoute := range r.TLSRoutes {
tlsRoute := tlsRoute
err := pr.resourcePrinter.PrintObj(&tlsRoute, os.Stdout)
if err != nil {
fmt.Printf("# Error printing %s TLSRoute: %v\n", tlsRoute.Name, err)
}
}
}
for _, r := range gatewayResources {
resourceCount += len(r.TCPRoutes)
for _, tcpRoute := range r.TCPRoutes {
tcpRoute := tcpRoute
err := pr.resourcePrinter.PrintObj(&tcpRoute, os.Stdout)
if err != nil {
fmt.Printf("# Error printing %s TCPRoute: %v\n", tcpRoute.Name, err)
}
}
}
for _, r := range gatewayResources {
resourceCount += len(r.UDPRoutes)
for _, udpRoute := range r.UDPRoutes {
udpRoute := udpRoute
err := pr.resourcePrinter.PrintObj(&udpRoute, os.Stdout)
if err != nil {
fmt.Printf("# Error printing %s UDPRoute: %v\n", udpRoute.Name, err)
}
}
}
for _, r := range gatewayResources {
resourceCount += len(r.ReferenceGrants)
for _, referenceGrant := range r.ReferenceGrants {
referenceGrant := referenceGrant
err := pr.resourcePrinter.PrintObj(&referenceGrant, os.Stdout)
if err != nil {
fmt.Printf("# Error printing %s ReferenceGrant: %v\n", referenceGrant.Name, err)
}
}
}
if resourceCount == 0 {
msg := "No resources found"
if pr.namespaceFilter != "" {
msg = fmt.Sprintf("%s in %s namespace", msg, pr.namespaceFilter)
}
fmt.Println(msg)
}
}
// initializeResourcePrinter assign a specific type of printers.ResourcePrinter
// based on the outputFormat of the printRunner struct.
func (pr *PrintRunner) initializeResourcePrinter() error {
switch pr.outputFormat {
case "yaml", "":
pr.resourcePrinter = &printers.YAMLPrinter{}
return nil
case "json":
pr.resourcePrinter = &printers.JSONPrinter{}
return nil
default:
return fmt.Errorf("%s is not a supported output format", pr.outputFormat)
}
}
// initializeNamespaceFilter initializes the correct namespace filter for resource processing with these scenarios:
// 1. If the --all-namespaces flag is used, it processes all resources, regardless of whether they are from the cluster or file.
// 2. If namespace is specified, it filters resources based on that namespace.
// 3. If no namespace is specified and reading from the cluster, it attempts to get the namespace from the cluster; if unsuccessful, initialization fails.
// 4. If no namespace is specified and reading from a file, it attempts to get the namespace from the cluster; if unsuccessful, it reads all resources.
func (pr *PrintRunner) initializeNamespaceFilter() error {
// When we should use all namespaces, empty string is used as the filter.
if pr.allNamespaces {
pr.namespaceFilter = ""
return nil
}
// If namespace flag is not specified, try to use the default namespace from the cluster
if pr.namespace == "" {
ns, err := getNamespaceInCurrentContext()
if err != nil && pr.inputFile == "" {
// When asked to read from the cluster, but getting the current namespace
// failed for whatever reason - do not process the request.
return err
}
// If err is nil we got the right filtered namespace.
// If the input file is specified, and we failed to get the namespace, use all namespaces.
pr.namespaceFilter = ns
return nil
}
pr.namespaceFilter = pr.namespace
return nil
}
func newPrintCommand() *cobra.Command {
pr := &PrintRunner{}
var printFlags genericclioptions.JSONYamlPrintFlags
allowedFormats := printFlags.AllowedFormats()
// printCmd represents the print command. It prints HTTPRoutes and Gateways
// generated from Ingress resources.
var cmd = &cobra.Command{
Use: "print",
Short: "Prints Gateway API objects generated from ingress and provider-specific resources.",
RunE: pr.PrintGatewayAPIObjects,
}
cmd.Flags().StringVarP(&pr.outputFormat, "output", "o", "yaml",
fmt.Sprintf(`Output format. One of: (%s).`, strings.Join(allowedFormats, ", ")))
cmd.Flags().StringVar(&pr.inputFile, "input-file", "",
`Path to the manifest file. When set, the tool will read ingresses from the file instead of reading from the cluster. Supported files are yaml and json.`)
cmd.Flags().StringVarP(&pr.namespace, "namespace", "n", "",
`If present, the namespace scope for this CLI request.`)
cmd.Flags().BoolVarP(&pr.allNamespaces, "all-namespaces", "A", false,
`If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even
if specified with --namespace.`)
cmd.Flags().StringSliceVar(&pr.providers, "providers", i2gw.GetSupportedProviders(),
fmt.Sprintf("If present, the tool will try to convert only resources related to the specified providers, supported values are %v.", i2gw.GetSupportedProviders()))
pr.providerSpecificFlags = make(map[string]*string)
for provider, flags := range i2gw.GetProviderSpecificFlagDefinitions() {
for _, flag := range flags {
flagName := fmt.Sprintf("%s-%s", provider, flag.Name)
pr.providerSpecificFlags[flagName] = cmd.Flags().String(flagName, flag.DefaultValue, fmt.Sprintf("Provider-specific: %s. %s", provider, flag.Description))
}
}
cmd.MarkFlagsMutuallyExclusive("namespace", "all-namespaces")
return cmd
}
// getNamespaceInCurrentContext returns the namespace in the current active context of the user.
func getNamespaceInCurrentContext() (string, error) {
loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
kubeConfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, &clientcmd.ConfigOverrides{})
currentNamespace, _, err := kubeConfig.Namespace()
return currentNamespace, err
}
// getProviderSpecificFlags returns the provider specific flags input by the user.
// The flags are returned in a map where the key is the provider name and the value is a map of flag name to flag value.
func (pr *PrintRunner) getProviderSpecificFlags() map[string]map[string]string {
providerSpecificFlags := make(map[string]map[string]string)
for flagName, value := range pr.providerSpecificFlags {
provider, found := lo.Find(pr.providers, func(p string) bool { return strings.HasPrefix(flagName, fmt.Sprintf("%s-", p)) })
if !found {
log.Printf("Warning: Ignoring flag %s as it does not match any of the providers", flagName)
continue
}
flagNameWithoutProvider := strings.TrimPrefix(flagName, fmt.Sprintf("%s-", provider))
if providerSpecificFlags[provider] == nil {
providerSpecificFlags[provider] = make(map[string]string)
}
providerSpecificFlags[provider][flagNameWithoutProvider] = *value
}
return providerSpecificFlags
}