blob: a42b6d815b2e5e119b4ff79ba117834a859379fe [file] [log] [blame]
Koren Lev19ca78f2018-11-21 18:46:54 +02001package main
2
3import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "git.fd.io/govpp.git/examples/bin_api/vpe"
8)
9
10type jsonVppDetails struct {
11 Program string `json:"program"`
12 Version string `json:"version"`
13 BuildDate string `json:"build_date"`
14 BuildDirectory string `json:"build_directory"`
15}
16
17type jsonVppInterface struct {
18 Index uint32 `json:"if_index"`
19 Name string `json:"if_name"`
20 Tag string `json:"if_tag"`
21 MacAddress string `json:"if_mac"`
22 AdminState uint8 `json:"if_admin_state"`
23 LinkState uint8 `json:"if_link_state"`
24 LinkMTU uint16 `json:"if_link_mtu"`
25 SubDot1ad uint8 `json:"if_sub_dot1ad"`
26 SubID uint32 `json:"if_sub_id"`
27
28 TxBytes uint64 `json:"if_tx_bytes"`
29 TxPackets uint64 `json:"if_tx_packets"`
30 TxErrors uint64 `json:"if_tx_errors"`
31 RxBytes uint64 `json:"if_rx_bytes"`
32 RxPackets uint64 `json:"if_rx_packets"`
33 RxErrors uint64 `json:"if_rx_errors"`
34 Drops uint64 `json:"if_drops"`
35 Punts uint64 `json:"if_punts"`
36}
37
38type jsonVppPayload struct {
39 *jsonVppDetails `json:"vpp_details"`
40 Interfaces []*jsonVppInterface `json:"interfaces"`
41}
42
43func bytesToString(b []byte) string {
44 return string(bytes.Split(b, []byte{0})[0])
45}
46
47func toJSONVppDetails(svReply *vpe.ShowVersionReply) *jsonVppDetails {
48 return &jsonVppDetails{
49 Program: bytesToString(svReply.Program),
50 Version: bytesToString(svReply.Version),
51 BuildDate: bytesToString(svReply.BuildDate),
52 BuildDirectory: bytesToString(svReply.BuildDirectory),
53 }
54}
55
56func toJSONVppInterface(vppIf *vppInterface) *jsonVppInterface {
57 return &jsonVppInterface{
58 Index: vppIf.SwIfIndex,
59 Name: bytesToString(vppIf.InterfaceName),
60 Tag: bytesToString(vppIf.Tag),
61 MacAddress: parseMacAddress(vppIf.L2Address, vppIf.L2AddressLength),
62 AdminState: vppIf.AdminUpDown,
63 LinkState: vppIf.LinkUpDown,
64 LinkMTU: vppIf.LinkMtu,
65 SubDot1ad: vppIf.SubDot1ad,
66 SubID: vppIf.SubID,
67 TxBytes: vppIf.Stats.TxBytes,
68 TxPackets: vppIf.Stats.TxPackets,
69 TxErrors: vppIf.Stats.TxErrors,
70 RxBytes: vppIf.Stats.RxBytes,
71 RxPackets: vppIf.Stats.RxPackets,
72 RxErrors: vppIf.Stats.RxErrors,
73 Drops: vppIf.Stats.Drops,
74 Punts: vppIf.Stats.Punts,
75 }
76}
77
78func toJSONVppPayload(svReply *vpe.ShowVersionReply, vppIfs []*vppInterface) *jsonVppPayload {
79 p := &jsonVppPayload{jsonVppDetails: toJSONVppDetails(svReply), Interfaces: make([]*jsonVppInterface, len(vppIfs))}
80 for index, vppIf := range vppIfs {
81 p.Interfaces[index] = toJSONVppInterface(vppIf)
82 }
83 return p
84}
85
86func dumpToJSONString(v *vppConnector) (string, error) {
87 payload := toJSONVppPayload(&v.VppDetails, v.Interfaces)
88 jsonBytes, err := json.Marshal(payload)
89 if err != nil {
90 return "", fmt.Errorf("failed to dump to json: %v", err)
91 }
92 return string(jsonBytes), nil
93}