1// Copyright 2019 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
15package compare
16
17import (
18	"encoding/json"
19	"fmt"
20	"io"
21
22	"istio.io/istio/istioctl/pkg/util/configdump"
23)
24
25// Comparator diffs between a config dump from Pilot and one from Envoy
26type Comparator struct {
27	envoy, pilot *configdump.Wrapper
28	w            io.Writer
29	context      int
30	location     string
31}
32
33// NewComparator is a comparator constructor
34func NewComparator(w io.Writer, pilotResponses map[string][]byte, envoyResponse []byte) (*Comparator, error) {
35	c := &Comparator{}
36	for _, resp := range pilotResponses {
37		pilotDump := &configdump.Wrapper{}
38		err := json.Unmarshal(resp, pilotDump)
39		if err != nil {
40			continue
41		}
42		c.pilot = pilotDump
43		break
44	}
45	if c.pilot == nil {
46		return nil, fmt.Errorf("unable to find config dump in Pilot responses")
47	}
48	envoyDump := &configdump.Wrapper{}
49	err := json.Unmarshal(envoyResponse, envoyDump)
50	if err != nil {
51		return nil, err
52	}
53	c.envoy = envoyDump
54	c.w = w
55	c.context = 7
56	c.location = "Local" // the time.Location for formatting time.Time instances
57	return c, nil
58}
59
60// Diff prints a diff between Pilot and Envoy to the passed writer
61func (c *Comparator) Diff() error {
62	if err := c.ClusterDiff(); err != nil {
63		return err
64	}
65	if err := c.ListenerDiff(); err != nil {
66		return err
67	}
68	return c.RouteDiff()
69}
70