Skip to content
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
3 changes: 2 additions & 1 deletion cmd/internal/cmd/flow/flow.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,13 +133,14 @@ func runFlows(p *printer.Printer) error {
}
}

gen := fakeflow.NewFaker()
for i := range opts.count {
// used to get a random node name
idx := rand.IntN(len(nodesIPs))
// add a small amount of jitter to the timestamps so they don't have perfect time gaps
jitter := rand.Int64N(int64(winRange))
t := since.Add(time.Duration(i)*winRange + time.Duration(jitter))
flow := fakeflow.New(
flow := gen.NewFlow(
fakeflow.WithFlowTime(t),
fakeflow.WithFlowNodeName(nodesIPs[idx].name),
fakeflow.WithFlowIP(nodesIPs[idx].ip),
Expand Down
3 changes: 2 additions & 1 deletion cmd/internal/cmd/ip/ip.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,9 @@ func runIPs(cmd *cobra.Command) error {
ipOptions = append(ipOptions, fake.WithIPCIDR(opts.cidr))
}

gen := fake.New()
for range opts.count {
fmt.Fprintln(cmd.OutOrStdout(), fake.IP(ipOptions...))
fmt.Fprintln(cmd.OutOrStdout(), gen.IP(ipOptions...))
}
return nil
}
3 changes: 2 additions & 1 deletion cmd/internal/cmd/mac/mac.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,9 @@ func New() *cobra.Command {
}

func runMACs(cmd *cobra.Command) error {
gen := fake.New()
for range opts.count {
fmt.Fprintln(cmd.OutOrStdout(), fake.MAC())
fmt.Fprintln(cmd.OutOrStdout(), gen.MAC())
}
return nil
}
1 change: 1 addition & 0 deletions data.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ var apps = []string{
"wordpress",
"zookeeper",
}

var labels = []string{
"io.cilium/app",
"k8s-app",
Expand Down
92 changes: 92 additions & 0 deletions fake.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
// SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Cilium

package fake

import (
"encoding/binary"
"io"
randv2 "math/rand/v2"
"strings"
)

// Faker is the main interface exposed to generate fake data.
type Faker interface { //nolint:interfacebloat
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is the rationale to introduce an interface rather than simply returning a struct? I don't really see the benefit of doing this.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is to hide the embedded rand and make the contract explicit. I'm neutral toward this though (we don't have to embed the rand stuff).

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have some issues with this approach as a 13 method interface will never be implemented in practice and, even if it were implemented elsewhere, every time we add a new method, we would break the existing implementation(s). So I'd really prefer we return a concrete *Faker. However, I think we should be able to address your concern regarding hiding the embedded rang as we can just not export it and keep it private.

// Adjective generates a random adjective.
Adjective() string
// AlphaNum generates a random alphanumeric string of the given length.
AlphaNum(length int) string
// App generates a random software application name.
App() string
// Noun generates a random noun.
Noun() string
// Name generates a random name.
Name() string
// Names generates a random set of names. It panics if n < 0.
Names(n int) []string
// DeploymentTier generates a random software deployment tier such as prod,
// staging, etc.
DeploymentTier() string

// K8sLabels generates a random set of Kubernetes labels.
K8sLabels() []string
// K8sNamespace generates a random Kubernetes namespace name.
K8sNamespace() string
// K8sNodeName generates a random Kubernetes node name.
K8sNodeName() string
// K8sPodName generates a random Kubernetes pod name.
K8sPodName() string

// MAC generates a random MAC address.
MAC() string
// IP generates a random IP address. Options may be provided to specify a
// network for the address or if it should be IPv4 or IPv6.
IP(options ...IPOption) string
// Port generates a random port number between 1 and 65535 or in the range
// specified by the given option.
Port(options ...PortOption) uint32
}

// New creates a new Faker using a random seed.
func New() Faker {
// NOTE: We seed from the global math/rand/v2 source rather than
// crypto/rand to avoid errors handling; the faker should not be used for
// security-sensitive purposes. We use ChaCha8 rather than PCG as ChaCha8
// implements io.Reader.
var seed [32]byte
for i := range 4 {
binary.LittleEndian.PutUint64(seed[i*8:], randv2.Uint64())
}
return NewWithSource(randv2.NewChaCha8(seed))
}

// RandSourceReader is a random source that also implements io.Reader.
type RandSourceReader interface {
randv2.Source
io.Reader
}

// NewWithSource creates a new Faker using the given random source. Useful to
// control the faker output, e.g. for testing.
func NewWithSource(src RandSourceReader) Faker {
return &faker{
Rand: randv2.New(src),
Reader: src,
}
}

// faker is a private struct implementing Faker.
type faker struct {
*randv2.Rand
io.Reader
}

// join3 is a helper to build a string composed of three parts.
func join3(left, middle, right string) string {
var sb strings.Builder
sb.Grow(len(left) + len(middle) + len(right))
sb.WriteString(left)
sb.WriteString(middle)
sb.WriteString(right)
return sb.String()
Comment thread
kaworu marked this conversation as resolved.
}
8 changes: 3 additions & 5 deletions flow/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,10 @@
package flow

import (
"math/rand/v2"

flowpb "github.com/cilium/cilium/api/v1/flow"
)

// AuthType generates a random AuthType.
func AuthType() flowpb.AuthType {
return flowpb.AuthType(rand.IntN(len(flowpb.AuthType_name))) //nolint:gosec
// AuthType implements FlowFaker for flowfaker.
func (f *flowfaker) AuthType() flowpb.AuthType {
return flowpb.AuthType(f.IntN(len(flowpb.AuthType_name))) //nolint:gosec
}
16 changes: 9 additions & 7 deletions flow/drop.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@
package flow

import (
"math/rand/v2"

flowpb "github.com/cilium/cilium/api/v1/flow"
)

Expand Down Expand Up @@ -50,20 +48,24 @@ func WithDropReasonSubSet(dropReasons []flowpb.DropReason) DropReasonOption {
})
}

// DropReason generates a DropReason. Options may be provided to customize the
// drop reasons to return.
func DropReason(options ...DropReasonOption) flowpb.DropReason {
// DropReason implements FlowFaker for flowfaker.
func (f *flowfaker) DropReason(options ...DropReasonOption) flowpb.DropReason {
// FIXME: evaluating all the options here for a single drop reason returned
// feels like we're paying a ton of overhead as soon as an option is given.
// Maybe consider moving this to the fake constructor, with maybe override
// possible on generation for special cases only?
opts := dropReasonOptions{
nonDropProbability: 0.999,
}
for _, opt := range options {
opt.apply(&opts)
}

if f := rand.Float64(); f < opts.nonDropProbability {
if r := f.Float64(); r < opts.nonDropProbability {
return flowpb.DropReason_DROP_REASON_UNKNOWN
}

// FIXME: extract the static default set to be computed only once.
if opts.set == nil {
opts.set = make([]flowpb.DropReason, 0, len(flowpb.DropReason_name)-1)
for k := range flowpb.DropReason_name {
Expand All @@ -72,5 +74,5 @@ func DropReason(options ...DropReasonOption) flowpb.DropReason {
}
}
}
return opts.set[rand.IntN(len(opts.set))]
return opts.set[f.IntN(len(opts.set))]
}
29 changes: 13 additions & 16 deletions flow/endpoint.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,7 @@
package flow

import (
"math/rand/v2"

flowpb "github.com/cilium/cilium/api/v1/flow"
"github.com/cilium/fake"
)

type endpointOptions struct {
Expand Down Expand Up @@ -71,20 +68,20 @@ func WithEndpointWorkloads(workloads map[string]string) EndpointOption {

// Endpoint generates a random Endpoint. Options may be provided to customize
// the endpoint to return.
func Endpoint(options ...EndpointOption) *flowpb.Endpoint {
func (f *flowfaker) Endpoint(options ...EndpointOption) *flowpb.Endpoint {
opts := endpointOptions{
namespace: fake.K8sNamespace(),
podName: fake.K8sPodName(),
labels: fake.K8sLabels(),
workloads: fakeWorkloads(),
namespace: f.K8sNamespace(),
podName: f.K8sPodName(),
labels: f.K8sLabels(),
workloads: f.fakeWorkloads(),
}
for _, opt := range options {
opt.apply(&opts)
}

return &flowpb.Endpoint{
ID: rand.Uint32(),
Identity: rand.Uint32(),
ID: f.Uint32(),
Identity: f.Uint32(),
ClusterName: opts.cluster,
Namespace: opts.namespace,
Labels: opts.labels,
Expand All @@ -105,15 +102,15 @@ var workloadKinds []string = []string{
"StatefulSet",
}

func fakeWorkloads() map[string]string {
func (f *flowfaker) fakeWorkloads() map[string]string {
workloads := map[string]string{
fake.App(): workloadKinds[rand.IntN(len(workloadKinds))],
f.App(): workloadKinds[f.IntN(len(workloadKinds))],
}
if rand.IntN(10) == 0 { // 10% chance of having more than one workload.
workloads[fake.App()] = workloadKinds[rand.IntN(len(workloadKinds))]
if f.IntN(10) == 0 { // 10% chance of having more than one workload.
workloads[f.App()] = workloadKinds[f.IntN(len(workloadKinds))]
}
if rand.IntN(100) == 0 { // 1% chance of having more than two workloads.
workloads[fake.App()] = workloadKinds[rand.IntN(len(workloadKinds))]
if f.IntN(100) == 0 { // 1% chance of having more than two workloads.
workloads[f.App()] = workloadKinds[f.IntN(len(workloadKinds))]
}
return workloads
}
Expand Down
10 changes: 4 additions & 6 deletions flow/event_type.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@
package flow

import (
"math/rand/v2"

flowpb "github.com/cilium/cilium/api/v1/flow"
"github.com/cilium/cilium/pkg/monitor/api"
)
Expand All @@ -21,15 +19,15 @@ var allEventTypes = []int32{
api.MessageTypeAgent,
}

// EventType generates a random EventType.
func EventType() *flowpb.CiliumEventType {
typ := allEventTypes[rand.IntN(len(allEventTypes))]
// EventType implements FlowFaker for flowfaker.
func (f *flowfaker) EventType() *flowpb.CiliumEventType {
typ := allEventTypes[f.IntN(len(allEventTypes))]
if typ == api.MessageTypeUnspec {
return nil
}
return &flowpb.CiliumEventType{
Type: typ,
// NOTE: AgentNotify* are the most numerous.
SubType: int32(rand.IntN(13)), //nolint:gosec
SubType: int32(f.IntN(13)), //nolint:gosec
}
}
84 changes: 84 additions & 0 deletions flow/fake.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
// SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Cilium

package flow

import (
"encoding/binary"
"io"
randv2 "math/rand/v2"

"github.com/cilium/fake"
"google.golang.org/protobuf/types/known/wrapperspb"

flowpb "github.com/cilium/cilium/api/v1/flow"
)

// FlowFaker is the main interface exposed to generate fake flow data.
type FlowFaker interface { //nolint:interfacebloat
// AuthType generates a random AuthType.
AuthType() flowpb.AuthType
// DropReason generates a DropReason.
DropReason(options ...DropReasonOption) flowpb.DropReason
// Endpoint generates a random Endpoint.
Endpoint(options ...EndpointOption) *flowpb.Endpoint
// EventType generates a random EventType.
EventType() *flowpb.CiliumEventType
// New generates a random Hubble Flow.
NewFlow(options ...Option) *flowpb.Flow
// ICMPv4 generates a random flow ICMPv4 struct.
ICMPv4() *flowpb.ICMPv4
// ICMPv6 generates a random flow ICMPv6 struct.
ICMPv6() *flowpb.ICMPv6
// IP generates a random flow IP struct.
IP(options ...IPOption) *flowpb.IP
// IsReply returns either nil, or a wrapped boolean value reprenting true,
// or a wrapped boolean value reprenting false, with equal probability.
IsReply() *wrapperspb.BoolValue
// Policies generates a list of random policy references.
Policies() []*flowpb.Policy
// Layer4 generates a layer 4. If no option is provided, it will be TCP.
Layer4(options ...Layer4Option) *flowpb.Layer4
// Service generates a random Service.
Service(options ...ServiceOption) *flowpb.Service
// TraceObservationPoint generates a random TraceObservationPoint.
TraceObservationPoint() flowpb.TraceObservationPoint
// TraceReason generates a random TraceReason.
TraceReason() flowpb.TraceReason
// TraceContext generates a TraceContext.
TraceContext(options ...TraceContextOption) *flowpb.TraceContext
// TrafficDirection generates a random TrafficDirection.
TrafficDirection() flowpb.TrafficDirection
// Verdict generates a FORWARDED or DROPPPED verdict randomly.
Verdict(options ...VerdictOption) flowpb.Verdict
}

// NewFaker creates a new Faker using a random seed.
func NewFaker() FlowFaker {
// NOTE: We seed from the global math/rand/v2 source rather than
// crypto/rand to avoid errors handling; the faker should not be used for
// security-sensitive purposes. We use ChaCha8 rather than PCG as ChaCha8
// implements io.Reader.
var seed [32]byte
for i := range 4 {
binary.LittleEndian.PutUint64(seed[i*8:], randv2.Uint64())
}
return NewWithSource(randv2.NewChaCha8(seed))
}

// NewWithSource creates a new Faker using the given random source. Useful to
// control the faker output, e.g. for testing.
func NewWithSource(src fake.RandSourceReader) FlowFaker {
return &flowfaker{
Faker: fake.NewWithSource(src),
Rand: randv2.New(src),
Reader: src,
}
}

// faker is a private struct implementing Faker.
type flowfaker struct {
fake.Faker
*randv2.Rand
io.Reader
}
Loading
Loading