// Copyright 2018 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package procfs

import (
	
	
	
	
	
	

	
	
)

// CPUStat shows how much time the cpu spend in various stages.
type CPUStat struct {
	User      float64
	Nice      float64
	System    float64
	Idle      float64
	Iowait    float64
	IRQ       float64
	SoftIRQ   float64
	Steal     float64
	Guest     float64
	GuestNice float64
}

// SoftIRQStat represent the softirq statistics as exported in the procfs stat file.
// A nice introduction can be found at https://0xax.gitbooks.io/linux-insides/content/interrupts/interrupts-9.html
// It is possible to get per-cpu stats by reading `/proc/softirqs`.
type SoftIRQStat struct {
	Hi          uint64
	Timer       uint64
	NetTx       uint64
	NetRx       uint64
	Block       uint64
	BlockIoPoll uint64
	Tasklet     uint64
	Sched       uint64
	Hrtimer     uint64
	Rcu         uint64
}

// Stat represents kernel/system statistics.
type Stat struct {
	// Boot time in seconds since the Epoch.
	BootTime uint64
	// Summed up cpu statistics.
	CPUTotal CPUStat
	// Per-CPU statistics.
	CPU map[int64]CPUStat
	// Number of times interrupts were handled, which contains numbered and unnumbered IRQs.
	IRQTotal uint64
	// Number of times a numbered IRQ was triggered.
	IRQ []uint64
	// Number of times a context switch happened.
	ContextSwitches uint64
	// Number of times a process was created.
	ProcessCreated uint64
	// Number of processes currently running.
	ProcessesRunning uint64
	// Number of processes currently blocked (waiting for IO).
	ProcessesBlocked uint64
	// Number of times a softirq was scheduled.
	SoftIRQTotal uint64
	// Detailed softirq statistics.
	SoftIRQ SoftIRQStat
}

// Parse a cpu statistics line and returns the CPUStat struct plus the cpu id (or -1 for the overall sum).
func parseCPUStat( string) (CPUStat, int64, error) {
	 := CPUStat{}
	var  string

	,  := fmt.Sscanf(, "%s %f %f %f %f %f %f %f %f %f %f",
		&,
		&.User, &.Nice, &.System, &.Idle,
		&.Iowait, &.IRQ, &.SoftIRQ, &.Steal,
		&.Guest, &.GuestNice)

	if  != nil &&  != io.EOF {
		return CPUStat{}, -1, fmt.Errorf("%w: couldn't parse %q (cpu): %w", ErrFileParse, , )
	}
	if  == 0 {
		return CPUStat{}, -1, fmt.Errorf("%w: couldn't parse %q (cpu): 0 elements parsed", ErrFileParse, )
	}

	.User /= userHZ
	.Nice /= userHZ
	.System /= userHZ
	.Idle /= userHZ
	.Iowait /= userHZ
	.IRQ /= userHZ
	.SoftIRQ /= userHZ
	.Steal /= userHZ
	.Guest /= userHZ
	.GuestNice /= userHZ

	if  == "cpu" {
		return , -1, nil
	}

	,  := strconv.ParseInt([3:], 10, 64)
	if  != nil {
		return CPUStat{}, -1, fmt.Errorf("%w: couldn't parse %q (cpu/cpuid): %w", ErrFileParse, , )
	}

	return , , nil
}

// Parse a softirq line.
func parseSoftIRQStat( string) (SoftIRQStat, uint64, error) {
	 := SoftIRQStat{}
	var  uint64
	var  string

	,  := fmt.Sscanf(, "%s %d %d %d %d %d %d %d %d %d %d %d",
		&, &,
		&.Hi, &.Timer, &.NetTx, &.NetRx,
		&.Block, &.BlockIoPoll,
		&.Tasklet, &.Sched,
		&.Hrtimer, &.Rcu)

	if  != nil {
		return SoftIRQStat{}, 0, fmt.Errorf("%w: couldn't parse %q (softirq): %w", ErrFileParse, , )
	}

	return , , nil
}

// NewStat returns information about current cpu/process statistics.
// See https://www.kernel.org/doc/Documentation/filesystems/proc.txt
//
// Deprecated: Use fs.Stat() instead.
func () (Stat, error) {
	,  := NewFS(fs.DefaultProcMountPoint)
	if  != nil {
		return Stat{}, 
	}
	return .Stat()
}

// NewStat returns information about current cpu/process statistics.
// See: https://www.kernel.org/doc/Documentation/filesystems/proc.txt
//
// Deprecated: Use fs.Stat() instead.
func ( FS) () (Stat, error) {
	return .Stat()
}

// Stat returns information about current cpu/process statistics.
// See: https://www.kernel.org/doc/Documentation/filesystems/proc.txt
func ( FS) () (Stat, error) {
	 := .proc.Path("stat")
	,  := util.ReadFileNoStat()
	if  != nil {
		return Stat{}, 
	}
	,  := parseStat(bytes.NewReader(), )
	if  != nil {
		return Stat{}, 
	}
	return , nil
}

// parseStat parses the metrics from /proc/[pid]/stat.
func parseStat( io.Reader,  string) (Stat, error) {
	var (
		 = bufio.NewScanner()
		    = Stat{
			CPU: make(map[int64]CPUStat),
		}
		 error
	)

	// Increase default scanner buffer to handle very long `intr` lines.
	 := make([]byte, 0, 8*1024)
	.Buffer(, 1024*1024)

	for .Scan() {
		 := .Text()
		 := strings.Fields(.Text())
		// require at least <key> <value>
		if len() < 2 {
			continue
		}
		switch {
		case [0] == "btime":
			if .BootTime,  = strconv.ParseUint([1], 10, 64);  != nil {
				return Stat{}, fmt.Errorf("%w: couldn't parse %q (btime): %w", ErrFileParse, [1], )
			}
		case [0] == "intr":
			if .IRQTotal,  = strconv.ParseUint([1], 10, 64);  != nil {
				return Stat{}, fmt.Errorf("%w: couldn't parse %q (intr): %w", ErrFileParse, [1], )
			}
			 := [2:]
			.IRQ = make([]uint64, len())
			for ,  := range  {
				if .IRQ[],  = strconv.ParseUint(, 10, 64);  != nil {
					return Stat{}, fmt.Errorf("%w: couldn't parse %q (intr%d): %w", ErrFileParse, , , )
				}
			}
		case [0] == "ctxt":
			if .ContextSwitches,  = strconv.ParseUint([1], 10, 64);  != nil {
				return Stat{}, fmt.Errorf("%w: couldn't parse %q (ctxt): %w", ErrFileParse, [1], )
			}
		case [0] == "processes":
			if .ProcessCreated,  = strconv.ParseUint([1], 10, 64);  != nil {
				return Stat{}, fmt.Errorf("%w: couldn't parse %q (processes): %w", ErrFileParse, [1], )
			}
		case [0] == "procs_running":
			if .ProcessesRunning,  = strconv.ParseUint([1], 10, 64);  != nil {
				return Stat{}, fmt.Errorf("%w: couldn't parse %q (procs_running): %w", ErrFileParse, [1], )
			}
		case [0] == "procs_blocked":
			if .ProcessesBlocked,  = strconv.ParseUint([1], 10, 64);  != nil {
				return Stat{}, fmt.Errorf("%w: couldn't parse %q (procs_blocked): %w", ErrFileParse, [1], )
			}
		case [0] == "softirq":
			, ,  := parseSoftIRQStat()
			if  != nil {
				return Stat{}, 
			}
			.SoftIRQTotal = 
			.SoftIRQ = 
		case strings.HasPrefix([0], "cpu"):
			, ,  := parseCPUStat()
			if  != nil {
				return Stat{}, 
			}
			if  == -1 {
				.CPUTotal = 
			} else {
				.CPU[] = 
			}
		}
	}

	if  := .Err();  != nil {
		return Stat{}, fmt.Errorf("%w: couldn't parse %q: %w", ErrFileParse, , )
	}

	return , nil
}