//go:build linux

package cgroup_test

import (
	"context"
	"fmt"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"testing"
	"time"

	"github.com/alexfalkowski/go-linux/v2/cgroup"
	"github.com/alexfalkowski/go-linux/v2/internal/test"
	"github.com/stretchr/testify/require"
)

func ExampleCPUBandwidth() {
	bandwidth := cgroup.CPUBandwidth{Quota: 50 * time.Millisecond, Period: 100 * time.Millisecond}
	text, err := bandwidth.MarshalText()
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(string(text))
	// Output: 50000 100000
}

func ExampleCPUUtilization() {
	clamp := cgroup.CPUUtilization(1250)
	text, err := clamp.MarshalText()
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(string(text))
	// Output: 12.50
}

func ExampleParsePressure() {
	snapshot, err := cgroup.ParsePressure([]byte("some avg10=7.25 avg60=1.23 avg300=0.25 total=10000\n"))
	if err != nil {
		log.Fatal(err)
	}

	if some, ok := snapshot["some"]; ok {
		fmt.Printf("10-second trend %.2f%%, cumulative stall %d µs\n", some.Avg10, some.TotalMicroseconds)
	}
	// Output: 10-second trend 7.25%, cumulative stall 10000 µs
}

func ExampleParseEvents() {
	event, err := cgroup.ParseEvents([]byte("populated 1\nfrozen 0\n"))
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(event.Populated, event.Frozen)
	// Output: true false
}

func ExampleIDSet() {
	cpus := cgroup.IDSet{
		{First: 2, Last: 3},
		{First: 6, Last: 6},
	}
	text, err := cpus.MarshalText()
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(string(text))
	// Output: 2-3,6
}

func ExampleParseIOMax() {
	device := cgroup.Device{Major: 259, Minor: 0}
	limits, err := cgroup.ParseIOMax([]byte("259:0 rbps=1048576 wbps=max riops=max wiops=200\n"))
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(limits[device].ReadBPS, limits[device].WriteIOPS)
	// Output: 1048576 200
}

func ExampleParseRDMAMax() {
	limits, err := cgroup.ParseRDMAMax([]byte("rxe0 hca_handle=2 hca_object=128 \n"))
	if err != nil {
		log.Fatal(err)
	}

	device := cgroup.RDMADevice("rxe0")
	fmt.Println(limits[device][cgroup.HCAHandle], limits[device][cgroup.HCAObject])
	// Output: 2 128
}

func ExampleParseMiscMax() {
	limits, err := cgroup.ParseMiscMax([]byte("sev 2\nsev_es max\n"))
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(limits[cgroup.MiscSEV], limits[cgroup.MiscSEVES] == cgroup.MiscUnlimited)
	// Output: 2 true
}

func ExampleParseDmemValues() {
	limits, err := cgroup.ParseDmemValues([]byte("drm/0000:03:00.0/vram0 1073741824\ndrm/0000:03:00.0/stolen max\n"))
	if err != nil {
		log.Fatal(err)
	}

	region := cgroup.DmemRegion("drm/0000:03:00.0/vram0")
	fmt.Println(limits[region])
	// Output: 1073741824
}

func ExampleOpen() {
	group, err := cgroup.Open("/sys/fs/cgroup")
	if err != nil {
		log.Fatal(err)
	}
	defer group.Close()

	_, err = group.Controllers()
	if err != nil {
		log.Print(err)
		return
	}

	fmt.Println("opened cgroup v2 hierarchy")
	// Output: opened cgroup v2 hierarchy
}

// An empty workload with zswap accounting reports the following values. Kernels without a zswap counter omit the second line.
//
//	anonymous memory: 0 bytes
//	zswap memory: 0 bytes
func ExampleGroup_MemoryStat() {
	// CGROUP_WORKLOAD names a group with the memory controller enabled.
	group, err := cgroup.Open(os.Getenv("CGROUP_WORKLOAD"))
	if err != nil {
		panic(err)
	}
	defer group.Close()

	stats, err := group.MemoryStat()
	if err != nil {
		panic(err)
	}
	fmt.Printf("anonymous memory: %d bytes\n", stats["anon"])
	if zswap, available := stats["zswap"]; available {
		fmt.Printf("zswap memory: %d bytes\n", zswap)
	}
}

func TestMemoryStatExample(t *testing.T) {
	group, path := test.DelegatedCgroupWithPath(t)
	t.Setenv("CGROUP_WORKLOAD", path)

	stats, err := group.MemoryStat()
	require.NoError(t, err)
	want := "anonymous memory: 0 bytes\n"
	if _, available := stats["zswap"]; available {
		want += "zswap memory: 0 bytes\n"
	}
	require.Equal(t, want, test.ExampleOutput(t, ExampleGroup_MemoryStat))
}

// A new, empty workload reports its peak and local limit events.
//
//	peak tasks: 0
//	local task limit hits: 0
func ExampleGroup_PIDsPeak() {
	// CGROUP_WORKLOAD names a group with the pids controller enabled.
	group, err := cgroup.Open(os.Getenv("CGROUP_WORKLOAD"))
	if err != nil {
		panic(err)
	}
	defer group.Close()

	peak, err := group.PIDsPeak()
	if err != nil {
		panic(err)
	}
	fmt.Printf("peak tasks: %d\n", peak)

	events, err := group.PIDsEventsLocal()
	if err != nil {
		panic(err)
	}
	if hits, available := events["max"]; available {
		fmt.Printf("local task limit hits: %d\n", hits)
	}
}

func TestPIDsPeakExample(t *testing.T) {
	_, path := test.DelegatedCgroupWithPath(t)
	t.Setenv("CGROUP_WORKLOAD", path)

	require.Equal(t, "peak tasks: 0\nlocal task limit hits: 0\n", test.ExampleOutput(t, ExampleGroup_PIDsPeak))
}

// A group with two supported huge-page sizes reports how many reservation limits it set.
//
//	reservation limits set: 2
func ExampleGroup_SetHugeTLBMax() {
	group, err := cgroup.Open(os.Getenv("CGROUP_WORKLOAD"))
	if err != nil {
		panic(err)
	}
	defer group.Close()

	sizes, err := group.HugeTLBPageSizes()
	if err != nil {
		panic(err)
	}
	for _, size := range sizes {
		// Forbid new explicit huge-page reservations by this workload.
		if err := group.SetHugeTLBMax(size, cgroup.HugePageReservation, 0); err != nil {
			panic(err)
		}
	}
	fmt.Printf("reservation limits set: %d\n", len(sizes))
}

func TestHugeTLBMaxExample(t *testing.T) {
	parent, path := test.DelegatedCgroupWithPath(t)
	require.NoError(t, parent.SetControllers([]cgroup.Controller{cgroup.HugeTLB}, nil))
	test.CgroupChild(t, parent, "example")
	workloadPath := filepath.Join(path, "example")
	t.Setenv("CGROUP_WORKLOAD", workloadPath)

	output := test.ExampleOutput(t, ExampleGroup_SetHugeTLBMax)

	limits := test.HugeTLBReservationLimits(t, workloadPath)
	require.NotEmpty(t, limits)
	require.Equal(t, fmt.Sprintf("reservation limits set: %d\n", len(limits)), output)
	for name, limit := range limits {
		require.Equal(t, "0", limit, "reservation limit in %s", name)
	}
}

// The worker reports the observed frozen state before the deferred thaw.
//
//	workload frozen
func ExampleGroup_Freeze() {
	// Set CGROUP_WORKLOAD to the target group. Run outside its subtree and
	// coordinate all writes to its local freeze request until the operation ends.
	group, err := cgroup.Open(os.Getenv("CGROUP_WORKLOAD"))
	if err != nil {
		panic(err)
	}
	defer group.Close()

	requested, err := group.FreezeRequested()
	if err != nil {
		panic(err)
	}
	if requested {
		panic("workload already has a local freeze request")
	}

	watcher, err := group.WatchEvents()
	if err != nil {
		panic(err)
	}
	defer watcher.Close()
	if err := watcher.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil {
		panic(err)
	}

	if err := group.Freeze(); err != nil {
		panic(err)
	}
	defer func() {
		if err := group.Thaw(); err != nil {
			panic(err)
		}
	}()

	if err := waitForFrozen(group, watcher); err != nil {
		panic(err)
	}
	// The workload is paused. Perform maintenance before the deferred thaw.
	fmt.Println("workload frozen")
}

func TestFreezeExample(t *testing.T) {
	group, path := test.DelegatedCgroupWithPath(t)
	t.Setenv("CGROUP_WORKLOAD", path)

	require.Equal(t, "workload frozen\n", test.ExampleOutput(t, ExampleGroup_Freeze))

	require.False(t, test.Value(t, group.FreezeRequested))
}

func TestFreezeExamplePreservesExistingRequest(t *testing.T) {
	group, path := test.DelegatedCgroupWithPath(t)
	t.Setenv("CGROUP_WORKLOAD", path)
	require.NoError(t, group.Freeze())
	t.Cleanup(func() {
		require.NoError(t, group.Thaw())
	})

	require.PanicsWithValue(t, "workload already has a local freeze request", ExampleGroup_Freeze)
	require.True(t, test.Value(t, group.FreezeRequested))
}

func waitForFrozen(group *cgroup.Group, watcher *cgroup.EventWatcher) error {
	event, err := group.Events()
	if err != nil {
		return err
	}
	for !event.Frozen {
		event, err = watcher.Read()
		if err != nil {
			return err
		}
	}
	return nil
}

// The command exits successfully inside the delegated group.
//
//	exit code: 0
func ExampleGroup_Start() {
	// Set CGROUP_WORKLOAD to an empty, explicitly delegated leaf with task accounting.
	group, err := cgroup.Open(os.Getenv("CGROUP_WORKLOAD"))
	if err != nil {
		panic(err)
	}
	defer group.Close()

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	command := exec.CommandContext(ctx, "/bin/true")
	if err := group.Start(command); err != nil {
		panic(err)
	}
	if err := command.Wait(); err != nil {
		panic(err)
	}
	fmt.Printf("exit code: %d\n", command.ProcessState.ExitCode())
}

func TestStartExample(t *testing.T) {
	group, path := test.DelegatedCgroupWithPath(t)
	t.Setenv("CGROUP_WORKLOAD", path)

	require.Equal(t, "exit code: 0\n", test.ExampleOutput(t, ExampleGroup_Start))

	require.Equal(t, uint64(1), test.Value(t, group.PIDsPeak))
}
