istio.io/istio@v0.0.0-20240520182934-d79c90f27776/istioctl/pkg/writer/ztunnel/configdump/policies.go (about) 1 // Copyright Istio Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package configdump 16 17 import ( 18 "cmp" 19 "encoding/json" 20 "fmt" 21 "strings" 22 23 "sigs.k8s.io/yaml" 24 25 "istio.io/istio/pkg/maps" 26 "istio.io/istio/pkg/slices" 27 ) 28 29 // PolicyFilter is used to pass filter information into service based config writer print functions 30 type PolicyFilter struct { 31 Namespace string 32 } 33 34 // Verify returns true if the passed workload matches the filter fields 35 func (wf *PolicyFilter) Verify(pol *ZtunnelPolicy) bool { 36 if wf.Namespace != "" { 37 if !strings.EqualFold(pol.Namespace, wf.Namespace) { 38 return false 39 } 40 } 41 42 return true 43 } 44 45 // PrintServiceSummary prints a summary of the relevant services in the config dump to the ConfigWriter stdout 46 func (c *ConfigWriter) PrintPolicySummary(filter PolicyFilter) error { 47 w := c.tabwriter() 48 zDump := c.ztunnelDump 49 50 pols := slices.Filter(maps.Values(zDump.Policies), filter.Verify) 51 slices.SortFunc(pols, func(a, b *ZtunnelPolicy) int { 52 if r := cmp.Compare(a.Namespace, b.Namespace); r != 0 { 53 return r 54 } 55 return cmp.Compare(a.Name, b.Name) 56 }) 57 fmt.Fprintln(w, "NAMESPACE\tPOLICY NAME\tACTION\tSCOPE") 58 59 for _, pol := range pols { 60 fmt.Fprintf(w, "%v\t%v\t%v\t%v\n", 61 pol.Namespace, pol.Name, pol.Action, pol.Scope) 62 } 63 return w.Flush() 64 } 65 66 // PrintPolicyDump prints the relevant services in the config dump to the ConfigWriter stdout 67 func (c *ConfigWriter) PrintPolicyDump(filter PolicyFilter, outputFormat string) error { 68 zDump := c.ztunnelDump 69 policies := slices.Filter(maps.Values(zDump.Policies), filter.Verify) 70 slices.SortFunc(policies, func(a, b *ZtunnelPolicy) int { 71 if r := cmp.Compare(a.Namespace, b.Namespace); r != 0 { 72 return r 73 } 74 return cmp.Compare(a.Name, b.Name) 75 }) 76 out, err := json.MarshalIndent(policies, "", " ") 77 if err != nil { 78 return fmt.Errorf("failed to marshal policies: %v", err) 79 } 80 if outputFormat == "yaml" { 81 if out, err = yaml.JSONToYAML(out); err != nil { 82 return err 83 } 84 } 85 fmt.Fprintln(c.Stdout, string(out)) 86 return nil 87 }