istio.io/istio@v0.0.0-20240520182934-d79c90f27776/istioctl/pkg/writer/compare/listener.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 compare
    16  
    17  import (
    18  	"bytes"
    19  	"fmt"
    20  
    21  	"github.com/pmezard/go-difflib/difflib"
    22  
    23  	// Force import protos
    24  	_ "istio.io/istio/pilot/pkg/xds/filters"
    25  	"istio.io/istio/pkg/util/protomarshal"
    26  )
    27  
    28  // ListenerDiff prints a diff between Istiod and Envoy listeners to the passed writer
    29  func (c *Comparator) ListenerDiff() error {
    30  	envoyBytes, istiodBytes := &bytes.Buffer{}, &bytes.Buffer{}
    31  	envoyListenerDump, err := c.envoy.GetDynamicListenerDump(true)
    32  	if err != nil {
    33  		envoyBytes.WriteString(err.Error())
    34  	} else {
    35  		envoy, err := protomarshal.ToJSONWithAnyResolver(envoyListenerDump, "    ", &envoyResolver)
    36  		if err != nil {
    37  			return err
    38  		}
    39  		envoyBytes.WriteString(envoy)
    40  	}
    41  	istiodListenerDump, err := c.istiod.GetDynamicListenerDump(true)
    42  	if err != nil {
    43  		istiodBytes.WriteString(err.Error())
    44  	} else {
    45  		istiod, err := protomarshal.ToJSONWithAnyResolver(istiodListenerDump, "    ", &envoyResolver)
    46  		if err != nil {
    47  			return err
    48  		}
    49  		istiodBytes.WriteString(istiod)
    50  	}
    51  	diff := difflib.UnifiedDiff{
    52  		FromFile: "Istiod Listeners",
    53  		A:        difflib.SplitLines(istiodBytes.String()),
    54  		ToFile:   "Envoy Listeners",
    55  		B:        difflib.SplitLines(envoyBytes.String()),
    56  		Context:  c.context,
    57  	}
    58  	text, err := difflib.GetUnifiedDiffString(diff)
    59  	if err != nil {
    60  		return err
    61  	}
    62  	if text != "" {
    63  		fmt.Fprintln(c.w, "Listeners Don't Match")
    64  		fmt.Fprintln(c.w, text)
    65  	} else {
    66  		fmt.Fprintln(c.w, "Listeners Match")
    67  	}
    68  	return nil
    69  }