/
dump.go
227 lines (207 loc) · 5.75 KB
/
dump.go
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
// Copyright (c) 2019 Cisco and/or its affiliates.
//
// 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 commands
import (
"context"
"fmt"
"io"
"sort"
"strings"
"github.com/golang/protobuf/proto"
"github.com/olekukonko/tablewriter"
"github.com/spf13/cobra"
"go.ligato.io/cn-infra/v2/logging"
"go.ligato.io/vpp-agent/v3/cmd/agentctl/api/types"
agentcli "go.ligato.io/vpp-agent/v3/cmd/agentctl/cli"
"go.ligato.io/vpp-agent/v3/pkg/models"
"go.ligato.io/vpp-agent/v3/plugins/kvscheduler/api"
)
func NewDumpCommand(cli agentcli.Cli) *cobra.Command {
var (
opts DumpOptions
)
cmd := &cobra.Command{
Use: "dump MODEL [MODEL...]",
Short: "Dump running state",
Long: "Dumps actual running state",
Example: `
Dump everything
{{.CommandPath}} all
Dump VPP interfaces & routes
{{.CommandPath}} vpp.interfaces vpp.l3.routes
Dump all VPP data in JSON format
{{.CommandPath}} -f json vpp.*
Dump only VPP memif interfaces
{{.CommandPath}} -f '{{` + "`{{range .}}{{if eq .Value.Type.String \"MEMIF\" }}{{json .}}{{end}}{{end}}`" + `}}' vpp.interfaces
Dump everything currently defined at northbound
{{.CommandPath}} --view=NB all
Dump all VPP & Linux data directly from southband
{{.CommandPath}} --view=SB vpp.* linux.*
Dump all VPP & Linux data directly from southband
{{.CommandPath}} --view=SB all
`,
Args: func(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
fmt.Fprintf(cli.Err(), "You must specify models to dump. Use \"%s models\" for a complete list of known models.\n", cmd.Root().Name())
return fmt.Errorf("no models specified")
}
opts.Models = args
return opts.Validate()
},
RunE: func(cmd *cobra.Command, args []string) error {
return runDump(cli, opts)
},
}
flags := cmd.Flags()
flags.StringVar(&opts.View, "view", "cached", "Dump view type: cached, NB, SB")
flags.StringVar(&opts.Origin, "origin", "", "Show only data with specific origin: NB, SB, unknown")
flags.StringVarP(&opts.Format, "format", "f", "", "Format output (json|yaml|go-template|proto)")
return cmd
}
type DumpOptions struct {
Models []string
View string
Origin string
Format string
}
func (opts *DumpOptions) Validate() error {
// models
if opts.Models[0] == "all" {
opts.Models = []string{"*"}
}
// view
switch strings.ToLower(opts.View) {
case "cached", "cache", "":
opts.View = "cached"
case "nb", "north", "northbound":
opts.View = "NB"
case "sb", "south", "southbound":
opts.View = "SB"
default:
return fmt.Errorf("invalid view type: %q", opts.View)
}
// origin
switch strings.ToLower(opts.Origin) {
case "":
case "unknown":
opts.Origin = api.UnknownOrigin.String()
case "from-nb", "nb", "north", "northbound":
opts.Origin = api.FromNB.String()
case "from-sb", "sb", "south", "southbound":
opts.Origin = api.FromSB.String()
default:
return fmt.Errorf("invalid origin: %q", opts.Origin)
}
return nil
}
func runDump(cli agentcli.Cli, opts DumpOptions) error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
allModels, err := cli.Client().ModelList(ctx, types.ModelListOptions{
Class: "config",
})
if err != nil {
return err
}
var keyPrefixes []string
for _, m := range filterModelsByRefs(allModels, opts.Models) {
keyPrefixes = append(keyPrefixes, m.KeyPrefix)
}
if len(keyPrefixes) == 0 {
return fmt.Errorf("no matching models found for %q", opts.Models)
}
var (
errs Errors
dumps []api.KVWithMetadata
)
for _, keyPrefix := range keyPrefixes {
dump, err := cli.Client().SchedulerDump(ctx, types.SchedulerDumpOptions{
KeyPrefix: keyPrefix,
View: opts.View,
})
if err != nil {
errs = append(errs, fmt.Errorf("dump for %s failed: %v", keyPrefix, err))
continue
}
dumps = append(dumps, dump...)
}
if errs != nil {
logging.Debugf("dump finished with %d errors\n%v", len(errs), errs)
}
dumps = filterDumpByOrigin(dumps, opts.Origin)
sort.Slice(dumps, func(i, j int) bool {
return dumps[i].Key < dumps[j].Key
})
format := opts.Format
if len(format) == 0 {
printDumpTable(cli.Out(), dumps)
} else {
if err := formatAsTemplate(cli.Out(), format, dumps); err != nil {
return err
}
}
return nil
}
func filterDumpByOrigin(dumps []api.KVWithMetadata, origin string) []api.KVWithMetadata {
if origin == "" {
return dumps
}
var filtered []api.KVWithMetadata
for _, d := range dumps {
if !strings.EqualFold(d.Origin.String(), origin) {
continue
}
filtered = append(filtered, d)
}
return filtered
}
func printDumpTable(out io.Writer, dump []api.KVWithMetadata) {
table := tablewriter.NewWriter(out)
table.SetHeader([]string{
"Model", "Origin", "Value", "Metadata", "Key",
})
table.SetAutoMergeCells(true)
table.SetAutoWrapText(false)
table.SetRowLine(true)
for _, d := range dump {
val := yamlTmpl(d.Value)
var meta string
if d.Metadata != nil {
meta = yamlTmpl(d.Metadata)
}
var (
name = "-"
model string
orig = d.Origin
)
if m, err := models.GetModelForKey(d.Key); err == nil {
name, _ = m.ParseKey(d.Key)
model = m.Name()
if name == "" {
name = d.Key
}
}
val = fmt.Sprintf("# %s\n%s", proto.MessageName(d.Value), val)
var row []string
row = []string{
model,
orig.String(),
val,
meta,
name,
}
table.Append(row)
}
table.Render()
}