Skip to content

Commit

Permalink
feat(cli): Add json output to link, unlink, allow, and allow-scrapes …
Browse files Browse the repository at this point in the history
…commands (#12658)

We add an -o/--output flag to the remaining commands which render kubernetes resources and do not yet have this flag. The supported values for this flag are "yaml" (default) and "json". The commands are:

linkerd mulitcluster allow
linkerd multicluster link
linkerd multicluster unlink
linkerd viz allow-scrapes

Signed-off-by: Alex Leong <alex@buoyant.io>
  • Loading branch information
adleong committed Jun 14, 2024
1 parent 80a1803 commit 26eba44
Show file tree
Hide file tree
Showing 6 changed files with 88 additions and 26 deletions.
7 changes: 4 additions & 3 deletions multicluster/cmd/allow.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,15 @@ type (
namespace string
serviceAccountName string
ignoreCluster bool
output string
}
)

func newAllowCommand() *cobra.Command {
opts := allowOptions{
namespace: defaultMulticlusterNamespace,
ignoreCluster: false,
output: "yaml",
}

cmd := &cobra.Command{
Expand Down Expand Up @@ -69,16 +71,15 @@ func newAllowCommand() *cobra.Command {
if err != nil {
return err
}
stdout.Write(buf.Bytes())
stdout.Write([]byte("---\n"))

return nil
return pkgcmd.RenderYAMLAs(&buf, stdout, opts.output)
},
}

cmd.Flags().StringVar(&opts.namespace, "namespace", defaultMulticlusterNamespace, "The destination namespace for the service account.")
cmd.Flags().BoolVar(&opts.ignoreCluster, "ignore-cluster", false, "Ignore cluster configuration")
cmd.Flags().StringVar(&opts.serviceAccountName, "service-account-name", "", "The name of the multicluster access service account")
cmd.PersistentFlags().StringVarP(&opts.output, "output", "o", "yaml", "Output format. One of: json|yaml")

pkgcmd.ConfigureNamespaceFlagCompletion(
cmd, []string{"namespace"},
Expand Down
79 changes: 62 additions & 17 deletions multicluster/cmd/link.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package cmd

import (
"bytes"
"encoding/json"
"errors"
"fmt"
"os"
Expand Down Expand Up @@ -56,6 +57,7 @@ type (
gatewayPort uint32
ha bool
enableGateway bool
output string
}
)

Expand Down Expand Up @@ -181,9 +183,19 @@ A full list of configurable values can be found at https://github.com/linkerd/li
},
}

credsOut, err := yaml.Marshal(creds)
if err != nil {
return err
var credsOut []byte
if opts.output == "yaml" {
credsOut, err = yaml.Marshal(creds)
if err != nil {
return err
}
} else if opts.output == "json" {
credsOut, err = json.Marshal(creds)
if err != nil {
return err
}
} else {
return fmt.Errorf("output format %s not supported", opts.output)
}

destinationCreds := corev1.Secret{
Expand All @@ -204,9 +216,20 @@ A full list of configurable values can be found at https://github.com/linkerd/li
k8s.ConfigKeyName: kubeconfig,
},
}
destinationCredsOut, err := yaml.Marshal(destinationCreds)
if err != nil {
return err

var destinationCredsOut []byte
if opts.output == "yaml" {
destinationCredsOut, err = yaml.Marshal(destinationCreds)
if err != nil {
return err
}
} else if opts.output == "json" {
destinationCredsOut, err = json.Marshal(destinationCreds)
if err != nil {
return err
}
} else {
return fmt.Errorf("output format %s not supported", opts.output)
}

remoteDiscoverySelector, err := metav1.ParseToLabelSelector(opts.remoteDiscoverySelector)
Expand Down Expand Up @@ -287,9 +310,20 @@ A full list of configurable values can be found at https://github.com/linkerd/li
if err != nil {
return err
}
linkOut, err := yaml.Marshal(obj.Object)
if err != nil {
return err

var linkOut []byte
if opts.output == "yaml" {
linkOut, err = yaml.Marshal(obj.Object)
if err != nil {
return err
}
} else if opts.output == "json" {
linkOut, err = json.Marshal(obj.Object)
if err != nil {
return err
}
} else {
return fmt.Errorf("output format %s not supported", opts.output)
}

values, err := buildServiceMirrorValues(opts)
Expand All @@ -313,19 +347,23 @@ A full list of configurable values can be found at https://github.com/linkerd/li
return err
}
}
serviceMirrorOut, err := renderServiceMirror(values, valuesOverrides, opts.namespace)
serviceMirrorOut, err := renderServiceMirror(values, valuesOverrides, opts.namespace, opts.output)
if err != nil {
return err
}

separator := []byte("---\n")
if opts.output == "json" {
separator = []byte("\n")
}
stdout.Write(credsOut)
stdout.Write([]byte("---\n"))
stdout.Write(separator)
stdout.Write(destinationCredsOut)
stdout.Write([]byte("---\n"))
stdout.Write(separator)
stdout.Write(linkOut)
stdout.Write([]byte("---\n"))
stdout.Write(separator)
stdout.Write(serviceMirrorOut)
stdout.Write([]byte("---\n"))
stdout.Write(separator)

return nil
},
Expand All @@ -350,14 +388,15 @@ A full list of configurable values can be found at https://github.com/linkerd/li
cmd.Flags().Uint32Var(&opts.gatewayPort, "gateway-port", opts.gatewayPort, "If specified, overwrites gateway port when gateway service is not type LoadBalancer")
cmd.Flags().BoolVar(&opts.ha, "ha", opts.ha, "Enable HA configuration for the service-mirror deployment (default false)")
cmd.Flags().BoolVar(&opts.enableGateway, "gateway", opts.enableGateway, "If false, allows a link to be created against a cluster that does not have a gateway service")
cmd.Flags().StringVarP(&opts.output, "output", "o", "yaml", "Output format. One of: json|yaml")

pkgcmd.ConfigureNamespaceFlagCompletion(
cmd, []string{"namespace", "gateway-namespace"},
kubeconfigPath, impersonate, impersonateGroup, kubeContext)
return cmd
}

func renderServiceMirror(values *multicluster.Values, valuesOverrides map[string]interface{}, namespace string) ([]byte, error) {
func renderServiceMirror(values *multicluster.Values, valuesOverrides map[string]interface{}, namespace string, format string) ([]byte, error) {
files := []*chartloader.BufferedFile{
{Name: chartutil.ChartfileName},
{Name: "templates/service-mirror.yaml"},
Expand Down Expand Up @@ -420,14 +459,19 @@ func renderServiceMirror(values *multicluster.Values, valuesOverrides map[string
}

// Merge templates and inject
var out bytes.Buffer
var yamlBytes bytes.Buffer
for _, tmpl := range chart.Templates {
t := path.Join(chart.Metadata.Name, tmpl.Name)
if _, err := out.WriteString(renderedTemplates[t]); err != nil {
if _, err := yamlBytes.WriteString(renderedTemplates[t]); err != nil {
return nil, err
}
}

var out bytes.Buffer
err = pkgcmd.RenderYAMLAs(&yamlBytes, &out, format)
if err != nil {
return nil, err
}
return out.Bytes(), nil
}

Expand All @@ -450,6 +494,7 @@ func newLinkOptionsWithDefault() (*linkOptions, error) {
gatewayPort: 0,
ha: false,
enableGateway: true,
output: "yaml",
}, nil
}

Expand Down
2 changes: 1 addition & 1 deletion multicluster/cmd/link_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func TestServiceMirrorRender(t *testing.T) {
for i, tc := range testCases {
tc := tc
t.Run(fmt.Sprintf("%d: %s", i, tc.goldenFileName), func(t *testing.T) {
out, err := renderServiceMirror(tc.serviceMirrorValues, charts.MergeMaps(defaultValues, tc.overrides), "test")
out, err := renderServiceMirror(tc.serviceMirrorValues, charts.MergeMaps(defaultValues, tc.overrides), "test", "yaml")
if err != nil {
t.Fatalf("Failed to render templates: %v", err)
}
Expand Down
13 changes: 11 additions & 2 deletions multicluster/cmd/unlink.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,8 +105,16 @@ func newUnlinkCommand() *cobra.Command {
}

for _, r := range resources {
if err := r.RenderResource(stdout); err != nil {
log.Errorf("failed to render resource %s: %s", r.Name, err)
if opts.output == "yaml" {
if err := r.RenderResource(stdout); err != nil {
log.Errorf("failed to render resource %s: %s", r.Name, err)
}
} else if opts.output == "json" {
if err := r.RenderResourceJSON(stdout); err != nil {
log.Errorf("failed to render resource %s: %s", r.Name, err)
}
} else {
return fmt.Errorf("unsupported format: %s", opts.output)
}
}

Expand All @@ -116,6 +124,7 @@ func newUnlinkCommand() *cobra.Command {

cmd.Flags().StringVar(&opts.namespace, "namespace", defaultMulticlusterNamespace, "The namespace for the service account")
cmd.Flags().StringVar(&opts.clusterName, "cluster-name", "", "Cluster name")
cmd.Flags().StringVarP(&opts.output, "output", "o", "yaml", "Output format. One of: json|yaml")

pkgcmd.ConfigureNamespaceFlagCompletion(
cmd, []string{"namespace"},
Expand Down
1 change: 0 additions & 1 deletion test/integration/multicluster/testdata/allow.golden

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 10 additions & 2 deletions viz/cmd/allow-scrapes.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package cmd

import (
"os"
"bytes"
"text/template"

pkgcmd "github.com/linkerd/linkerd2/pkg/cmd"
Expand Down Expand Up @@ -118,6 +118,7 @@ type templateOptions struct {

// newCmdAllowScrapes creates a new cobra command `allow-scrapes`
func newCmdAllowScrapes() *cobra.Command {
output := "yaml"
options := templateOptions{
ExtensionName: ExtensionName,
ChartName: vizChartName,
Expand All @@ -136,10 +137,17 @@ linkerd viz allow-scrapes --namespace emojivoto | kubectl apply -f -`,
},
RunE: func(cmd *cobra.Command, args []string) error {
t := template.Must(template.New("allow-scrapes").Parse(allowScrapePolicy))
return t.Execute(os.Stdout, options)
var buf bytes.Buffer
err := t.Execute(&buf, options)
if err != nil {
return err
}

return pkgcmd.RenderYAMLAs(&buf, stdout, output)
},
}
cmd.Flags().StringVarP(&options.TargetNs, "namespace", "n", options.TargetNs, "The namespace in which to authorize Prometheus scrapes.")
cmd.Flags().StringVarP(&output, "output", "o", output, "Output format. One of: json|yaml")

pkgcmd.ConfigureNamespaceFlagCompletion(
cmd, []string{"n", "namespace"},
Expand Down

0 comments on commit 26eba44

Please sign in to comment.