package main

// Who writes to the disk: the bytes each process caused to be written to storage (write_bytes in
// /proc/<pid>/io), sampled once per rollup by the background worker. The difference since the
// previous look is summed per program (name, systemd unit, container) and the ten biggest writers
// go into the rollup. Other users' /proc/<pid>/io needs the detailed mode (PTRACE_MODE_READ).

import (
	"bytes"
	"sort"
	"strconv"
	"time"
)

type WriterOut struct {
	Name      string `json:"name"`
	Unit      string `json:"unit,omitempty"`
	Container string `json:"container,omitempty"`
	Bytes     int64  `json:"bytes"`
}

type wPrev struct {
	start uint64
	wb    uint64
}

type WriteTracker struct {
	prev   map[int]wPrev
	prevAt time.Time
	buf    []byte
}

func NewWriteTracker() *WriteTracker {
	return &WriteTracker{prev: map[int]wPrev{}, buf: make([]byte, 512)}
}

// parseWriteBytes reads write_bytes from /proc/<pid>/io.
func parseWriteBytes(b []byte) (uint64, bool) {
	i := bytes.Index(b, []byte("\nwrite_bytes: "))
	if i < 0 {
		if !bytes.HasPrefix(b, []byte("write_bytes: ")) {
			return 0, false
		}
		i = -1
	}
	rest := b[i+1+len("write_bytes: "):]
	if j := bytes.IndexByte(rest, '\n'); j >= 0 {
		rest = rest[:j]
	}
	return parseUintBytes(rest)
}

// Sample returns the top writers since the previous call (nil on the first one). bootTime turns
// the processes' start ticks into time: a process started since the previous look counts whole.
func (w *WriteTracker) Sample(procRoot string, procs []procRef, bootTime int64, users *UserCache, docker *DockerIndex, g *Gentle, now time.Time) []WriterOut {
	type d struct {
		pid   int
		delta uint64
	}
	var deltas []d
	next := make(map[int]wPrev, len(procs))
	first := w.prevAt.IsZero()
	prevTicks := uint64(0)
	if !first && bootTime > 0 {
		prevTicks = uint64(max(0, w.prevAt.Unix()-bootTime)) * clockTicks
	}
	for _, p := range procs {
		if p.Kernel || p.PID <= 0 {
			continue
		}
		g.Tick()
		n, err := readInto(procRoot+"/"+strconv.Itoa(p.PID)+"/io", w.buf)
		if err != nil {
			continue
		}
		wb, ok := parseWriteBytes(w.buf[:n])
		if !ok {
			continue
		}
		next[p.PID] = wPrev{start: p.Start, wb: wb}
		if first {
			continue
		}
		if pp, ok := w.prev[p.PID]; ok && pp.start == p.Start {
			if wb > pp.wb {
				deltas = append(deltas, d{p.PID, wb - pp.wb})
			}
		} else if p.Start >= prevTicks && wb > 0 { // started since the previous look
			deltas = append(deltas, d{p.PID, wb})
		}
	}
	w.prev, w.prevAt = next, now
	if first {
		return nil
	}
	sort.Slice(deltas, func(i, j int) bool { return deltas[i].delta > deltas[j].delta })
	if len(deltas) > 25 {
		deltas = deltas[:25]
	}
	agg := map[string]*WriterOut{}
	var order []string
	for _, x := range deltas {
		o := describeOwner(procRoot, x.pid, users, docker)
		if o.Name == "" {
			continue
		}
		k := o.Name + "|" + o.Unit + "|" + o.Container
		a := agg[k]
		if a == nil {
			a = &WriterOut{Name: o.Name, Unit: o.Unit, Container: o.Container}
			agg[k] = a
			order = append(order, k)
		}
		a.Bytes += int64(x.delta)
	}
	out := make([]WriterOut, 0, len(order))
	for _, k := range order {
		out = append(out, *agg[k])
	}
	sort.Slice(out, func(i, j int) bool { return out[i].Bytes > out[j].Bytes })
	if len(out) > 10 {
		out = out[:10]
	}
	return out
}
