// Command smallprog is a stand-in for a small Go utility. It runs in one of
// three modes and, after -report, prints one line of runtime memory stats to
// stderr. It then keeps running so that its RSS and CPU can be read from /proc.
package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"os"
	"runtime"
	"sync"
	"time"
)

var sink [][]byte

type record struct {
	Seq  int    `json:"seq"`
	Time string `json:"time"`
	Msg  string `json:"msg"`
}

// burst fans out 256 goroutines that allocate objects of 16 B to 4 KiB, keeps
// about 1 MiB of them, and returns. It models start-up or an occasional
// parallel job.
func burst() {
	var wg sync.WaitGroup
	var mu sync.Mutex
	for g := 0; g < 256; g++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for i := 0; i < 2000; i++ {
				b := make([]byte, 16<<(i%9))
				if i%500 == 0 {
					mu.Lock()
					sink = append(sink, b)
					mu.Unlock()
				}
			}
		}()
	}
	wg.Wait()
	runtime.GC()
}

// ticker runs 8 goroutines that each wake every 10 ms and JSON-encode a small
// record, like a sidecar that polls, formats, and forwards.
func ticker() {
	for g := 0; g < 8; g++ {
		go func() {
			enc := json.NewEncoder(discard{})
			for i := 0; ; i++ {
				enc.Encode(record{Seq: i, Time: time.Now().Format(time.RFC3339Nano), Msg: fmt.Sprintf("worker %d tick %d", g, i)})
				time.Sleep(10 * time.Millisecond)
			}
		}()
	}
}

type discard struct{}

func (discard) Write(p []byte) (int, error) { return len(p), nil }

func main() {
	mode := flag.String("mode", "idle", "idle, burst, or ticker")
	report := flag.Duration("report", 3*time.Second, "when to print runtime stats")
	flag.Parse()

	switch *mode {
	case "idle":
	case "burst":
		burst()
	case "ticker":
		ticker()
	default:
		fmt.Fprintln(os.Stderr, "unknown mode", *mode)
		os.Exit(2)
	}

	time.Sleep(*report)
	var s runtime.MemStats
	runtime.ReadMemStats(&s)
	kib := func(v uint64) uint64 { return v >> 10 }
	fmt.Fprintf(os.Stderr, "mode=%s procs=%d heap_inuse_kib=%d stack_inuse_kib=%d mspan_kib=%d mcache_kib=%d gc_sys_kib=%d other_sys_kib=%d num_gc=%d\n",
		*mode, runtime.GOMAXPROCS(0), kib(s.HeapInuse), kib(s.StackInuse), kib(s.MSpanInuse), kib(s.MCacheInuse), kib(s.GCSys), kib(s.OtherSys), s.NumGC)
	for {
		time.Sleep(time.Hour)
	}
}
