Skip to content

pkg/tcpip: impl json.Marshaler/Unmarshaler for StatCounter to Marshal/Unmarshal *Stats #11775

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions pkg/tcpip/tcpip.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ package tcpip

import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
Expand Down Expand Up @@ -1633,6 +1634,21 @@ func (s *StatCounter) String() string {
return strconv.FormatUint(s.Value(), 10)
}

// MarshalJSON implements json.Marshaler.MarshalJSON
func (s *StatCounter) MarshalJSON() ([]byte, error) {
return json.Marshal(s.Value())
}

// UnmarshalJSON implements json.Unmarshaler.UnmarshalJSON
func (s *StatCounter) UnmarshalJSON(data []byte) error {
var val uint64
if err := json.Unmarshal(data, &val); err != nil {
return err
}
s.count.Store(val)
return nil
}

// A MultiCounterStat keeps track of two counters at once.
//
// +stateify savable
Expand Down
23 changes: 23 additions & 0 deletions pkg/tcpip/tcpip_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package tcpip

import (
"bytes"
"encoding/json"
"fmt"
"io"
"net"
Expand Down Expand Up @@ -345,3 +346,25 @@ func padTo4(partial string) []byte {
}
return []byte(partial)
}

func TestStats_Marshal(t *testing.T) {
s := Stats{}.FillIn()
s.TCP.ForwardMaxInFlightDrop.Increment()
jb, err := json.Marshal(s)
if err != nil {
t.Fail()
}
if !bytes.Contains(jb, []byte(`"ForwardMaxInFlightDrop":1`)) {
t.Fatalf("Marshal did not contain ForwardMaxInFlightDrop")
}

todo := `{"TCP":{"ForwardMaxInFlightDrop":1}}`
var to Stats
err = json.Unmarshal([]byte(todo), &to)
if err != nil {
t.Fail()
}
if got := to.TCP.ForwardMaxInFlightDrop.Value(); got != uint64(1) {
t.Fatalf("got ForwardMaxInFlightDrop.Value() = %d, want = %d", got, uint64(1))
}
}