procfs

package module
v0.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 3, 2019 License: Apache-2.0 Imports: 15 Imported by: 1,007

README

procfs

This procfs package provides functions to retrieve system, kernel and process metrics from the pseudo-filesystems /proc and /sys.

WARNING: This package is a work in progress. Its API may still break in backwards-incompatible ways without warnings. Use it at your own risk.

GoDoc Build Status Go Report Card

Usage

The procfs library is organized by packages based on whether the gathered data is coming from /proc, /sys, or both. Each package contains an FS type which represents the path to either /proc, /sys, or both. For example, current cpu statistics are gathered from /proc/stat and are available via the root procfs package. First, the proc filesystem mount point is initialized, and then the stat information is read.

fs, err := procfs.NewFS("/proc")
stats, err := fs.Stat()

Some sub-packages such as blockdevice, require access to both the proc and sys filesystems.

    fs, err := blockdevice.NewFS("/proc", "/sys")
    stats, err := fs.ProcDiskstats()

Building and Testing

The procfs library is normally built as part of another application. However, when making changes to the library, the make test command can be used to run the API test suite.

Updating Test Fixtures

The procfs library includes a set of test fixtures which include many example files from the /proc and /sys filesystems. These fixtures are included as a ttar file which is extracted automatically during testing. To add/update the test fixtures, first ensure the fixtures directory is up to date by removing the existing directory and then extracting the ttar file using make fixtures/.unpacked or just make test.

rm -rf fixtures
make test

Next, make the required changes to the extracted files in the fixtures directory. When the changes are complete, run make update_fixtures to create a new fixtures.ttar file based on the updated fixtures directory. And finally, verify the changes using git diff fixtures.ttar.

Documentation

Overview

Package procfs provides functions to retrieve system, kernel and process metrics from the pseudo-filesystem proc.

Example:

package main

import (
	"fmt"
	"log"

	"github.com/prometheus/procfs"
)

func main() {
	p, err := procfs.Self()
	if err != nil {
		log.Fatalf("could not get process: %s", err)
	}

	stat, err := p.NewStat()
	if err != nil {
		log.Fatalf("could not get process stat: %s", err)
	}

	fmt.Printf("command:  %s\n", stat.Comm)
	fmt.Printf("cpu time: %fs\n", stat.CPUTime())
	fmt.Printf("vsize:    %dB\n", stat.VirtualMemory())
	fmt.Printf("rss:      %dB\n", stat.ResidentMemory())
}

Index

Constants

View Source
const DefaultMountPoint = fs.DefaultProcMountPoint

DefaultMountPoint is the common mount point of the proc filesystem.

Variables

This section is empty.

Functions

This section is empty.

Types

type BuddyInfo

type BuddyInfo struct {
	Node  string
	Zone  string
	Sizes []float64
}

A BuddyInfo is the details parsed from /proc/buddyinfo. The data is comprised of an array of free fragments of each size. The sizes are 2^n*PAGE_SIZE, where n is the array index.

type CPUStat

type CPUStat struct {
	User      float64
	Nice      float64
	System    float64
	Idle      float64
	Iowait    float64
	IRQ       float64
	SoftIRQ   float64
	Steal     float64
	Guest     float64
	GuestNice float64
}

CPUStat shows how much time the cpu spend in various stages.

type FS

type FS struct {
	// contains filtered or unexported fields
}

FS represents the pseudo-filesystem sys, which provides an interface to kernel data structures.

func NewDefaultFS added in v0.0.2

func NewDefaultFS() (FS, error)

NewDefaultFS returns a new proc FS mounted under the default proc mountPoint. It will error if the mount point directory can't be read or is a file.

func NewFS

func NewFS(mountPoint string) (FS, error)

NewFS returns a new proc FS mounted under the given proc mountPoint. It will error if the mount point directory can't be read or is a file.

func (FS) AllProcs

func (fs FS) AllProcs() (Procs, error)

AllProcs returns a list of all currently available processes.

func (FS) BuddyInfo added in v0.0.2

func (fs FS) BuddyInfo() ([]BuddyInfo, error)

NewBuddyInfo reads the buddyinfo statistics from the specified `proc` filesystem.

func (FS) IPVSBackendStatus added in v0.0.2

func (fs FS) IPVSBackendStatus() ([]IPVSBackendStatus, error)

IPVSBackendStatus reads and returns the status of all (virtual,real) server pairs from the specified `proc` filesystem.

func (FS) IPVSStats added in v0.0.2

func (fs FS) IPVSStats() (IPVSStats, error)

IPVSStats reads the IPVS statistics from the specified `proc` filesystem.

func (FS) MDStat added in v0.0.2

func (fs FS) MDStat() ([]MDStat, error)

MDStat parses an mdstat-file (/proc/mdstat) and returns a slice of structs containing the relevant info. More information available here: https://raid.wiki.kernel.org/index.php/Mdstat

func (FS) NetDev added in v0.0.2

func (fs FS) NetDev() (NetDev, error)

NetDev returns kernel/system statistics read from /proc/net/dev.

func (FS) NewNetUnix

func (fs FS) NewNetUnix() (*NetUnix, error)

NewNetUnix returns data read from /proc/net/unix.

func (FS) NewProc deprecated

func (fs FS) NewProc(pid int) (Proc, error)

NewProc returns a process for the given pid.

Deprecated: use fs.Proc() instead

func (FS) NewStat deprecated

func (fs FS) NewStat() (Stat, error)

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) NewXfrmStat

func (fs FS) NewXfrmStat() (XfrmStat, error)

NewXfrmStat reads the xfrm_stat statistics from the 'proc' filesystem.

func (FS) PSIStatsForResource added in v0.0.2

func (fs FS) PSIStatsForResource(resource string) (PSIStats, error)

PSIStatsForResource reads pressure stall information for the specified resource from /proc/pressure/<resource>. At time of writing this can be either "cpu", "memory" or "io".

func (FS) Proc added in v0.0.2

func (fs FS) Proc(pid int) (Proc, error)

Proc returns a process for the given pid.

func (FS) Self

func (fs FS) Self() (Proc, error)

Self returns a process for the current process.

func (FS) Stat added in v0.0.2

func (fs FS) Stat() (Stat, error)

Stat returns information about current cpu/process statistics. See https://www.kernel.org/doc/Documentation/filesystems/proc.txt

type IPVSBackendStatus

type IPVSBackendStatus struct {
	// The local (virtual) IP address.
	LocalAddress net.IP
	// The remote (real) IP address.
	RemoteAddress net.IP
	// The local (virtual) port.
	LocalPort uint16
	// The remote (real) port.
	RemotePort uint16
	// The local firewall mark
	LocalMark string
	// The transport protocol (TCP, UDP).
	Proto string
	// The current number of active connections for this virtual/real address pair.
	ActiveConn uint64
	// The current number of inactive connections for this virtual/real address pair.
	InactConn uint64
	// The current weight of this virtual/real address pair.
	Weight uint64
}

IPVSBackendStatus holds current metrics of one virtual / real address pair.

type IPVSStats

type IPVSStats struct {
	// Total count of connections.
	Connections uint64
	// Total incoming packages processed.
	IncomingPackets uint64
	// Total outgoing packages processed.
	OutgoingPackets uint64
	// Total incoming traffic.
	IncomingBytes uint64
	// Total outgoing traffic.
	OutgoingBytes uint64
}

IPVSStats holds IPVS statistics, as exposed by the kernel in `/proc/net/ip_vs_stats`.

type MDStat

type MDStat struct {
	// Name of the device.
	Name string
	// activity-state of the device.
	ActivityState string
	// Number of active disks.
	DisksActive int64
	// Total number of disks the device consists of.
	DisksTotal int64
	// Number of blocks the device holds.
	BlocksTotal int64
	// Number of blocks on the device that are in sync.
	BlocksSynced int64
}

MDStat holds info parsed from /proc/mdstat.

type Mount

type Mount struct {
	// Name of the device.
	Device string
	// The mount point of the device.
	Mount string
	// The filesystem type used by the device.
	Type string
	// If available additional statistics related to this Mount.
	// Use a type assertion to determine if additional statistics are available.
	Stats MountStats
}

A Mount is a device mount parsed from /proc/[pid]/mountstats.

type MountStats

type MountStats interface {
	// contains filtered or unexported methods
}

A MountStats is a type which contains detailed statistics for a specific type of Mount.

type MountStatsNFS

type MountStatsNFS struct {
	// The version of statistics provided.
	StatVersion string
	// The mount options of the NFS mount.
	Opts map[string]string
	// The age of the NFS mount.
	Age time.Duration
	// Statistics related to byte counters for various operations.
	Bytes NFSBytesStats
	// Statistics related to various NFS event occurrences.
	Events NFSEventsStats
	// Statistics broken down by filesystem operation.
	Operations []NFSOperationStats
	// Statistics about the NFS RPC transport.
	Transport NFSTransportStats
}

A MountStatsNFS is a MountStats implementation for NFSv3 and v4 mounts.

type NFSBytesStats

type NFSBytesStats struct {
	// Number of bytes read using the read() syscall.
	Read uint64
	// Number of bytes written using the write() syscall.
	Write uint64
	// Number of bytes read using the read() syscall in O_DIRECT mode.
	DirectRead uint64
	// Number of bytes written using the write() syscall in O_DIRECT mode.
	DirectWrite uint64
	// Number of bytes read from the NFS server, in total.
	ReadTotal uint64
	// Number of bytes written to the NFS server, in total.
	WriteTotal uint64
	// Number of pages read directly via mmap()'d files.
	ReadPages uint64
	// Number of pages written directly via mmap()'d files.
	WritePages uint64
}

A NFSBytesStats contains statistics about the number of bytes read and written by an NFS client to and from an NFS server.

type NFSEventsStats

type NFSEventsStats struct {
	// Number of times cached inode attributes are re-validated from the server.
	InodeRevalidate uint64
	// Number of times cached dentry nodes are re-validated from the server.
	DnodeRevalidate uint64
	// Number of times an inode cache is cleared.
	DataInvalidate uint64
	// Number of times cached inode attributes are invalidated.
	AttributeInvalidate uint64
	// Number of times files or directories have been open()'d.
	VFSOpen uint64
	// Number of times a directory lookup has occurred.
	VFSLookup uint64
	// Number of times permissions have been checked.
	VFSAccess uint64
	// Number of updates (and potential writes) to pages.
	VFSUpdatePage uint64
	// Number of pages read directly via mmap()'d files.
	VFSReadPage uint64
	// Number of times a group of pages have been read.
	VFSReadPages uint64
	// Number of pages written directly via mmap()'d files.
	VFSWritePage uint64
	// Number of times a group of pages have been written.
	VFSWritePages uint64
	// Number of times directory entries have been read with getdents().
	VFSGetdents uint64
	// Number of times attributes have been set on inodes.
	VFSSetattr uint64
	// Number of pending writes that have been forcefully flushed to the server.
	VFSFlush uint64
	// Number of times fsync() has been called on directories and files.
	VFSFsync uint64
	// Number of times locking has been attempted on a file.
	VFSLock uint64
	// Number of times files have been closed and released.
	VFSFileRelease uint64
	// Unknown.  Possibly unused.
	CongestionWait uint64
	// Number of times files have been truncated.
	Truncation uint64
	// Number of times a file has been grown due to writes beyond its existing end.
	WriteExtension uint64
	// Number of times a file was removed while still open by another process.
	SillyRename uint64
	// Number of times the NFS server gave less data than expected while reading.
	ShortRead uint64
	// Number of times the NFS server wrote less data than expected while writing.
	ShortWrite uint64
	// Number of times the NFS server indicated EJUKEBOX; retrieving data from
	// offline storage.
	JukeboxDelay uint64
	// Number of NFS v4.1+ pNFS reads.
	PNFSRead uint64
	// Number of NFS v4.1+ pNFS writes.
	PNFSWrite uint64
}

A NFSEventsStats contains statistics about NFS event occurrences.

type NFSOperationStats

type NFSOperationStats struct {
	// The name of the operation.
	Operation string
	// Number of requests performed for this operation.
	Requests uint64
	// Number of times an actual RPC request has been transmitted for this operation.
	Transmissions uint64
	// Number of times a request has had a major timeout.
	MajorTimeouts uint64
	// Number of bytes sent for this operation, including RPC headers and payload.
	BytesSent uint64
	// Number of bytes received for this operation, including RPC headers and payload.
	BytesReceived uint64
	// Duration all requests spent queued for transmission before they were sent.
	CumulativeQueueMilliseconds uint64
	// Duration it took to get a reply back after the request was transmitted.
	CumulativeTotalResponseMilliseconds uint64
	// Duration from when a request was enqueued to when it was completely handled.
	CumulativeTotalRequestMilliseconds uint64
}

A NFSOperationStats contains statistics for a single operation.

type NFSTransportStats

type NFSTransportStats struct {
	// The transport protocol used for the NFS mount.
	Protocol string
	// The local port used for the NFS mount.
	Port uint64
	// Number of times the client has had to establish a connection from scratch
	// to the NFS server.
	Bind uint64
	// Number of times the client has made a TCP connection to the NFS server.
	Connect uint64
	// Duration (in jiffies, a kernel internal unit of time) the NFS mount has
	// spent waiting for connections to the server to be established.
	ConnectIdleTime uint64
	// Duration since the NFS mount last saw any RPC traffic.
	IdleTimeSeconds uint64
	// Number of RPC requests for this mount sent to the NFS server.
	Sends uint64
	// Number of RPC responses for this mount received from the NFS server.
	Receives uint64
	// Number of times the NFS server sent a response with a transaction ID
	// unknown to this client.
	BadTransactionIDs uint64
	// A running counter, incremented on each request as the current difference
	// ebetween sends and receives.
	CumulativeActiveRequests uint64
	// A running counter, incremented on each request by the current backlog
	// queue size.
	CumulativeBacklog uint64

	// Maximum number of simultaneously active RPC requests ever used.
	MaximumRPCSlotsUsed uint64
	// A running counter, incremented on each request as the current size of the
	// sending queue.
	CumulativeSendingQueue uint64
	// A running counter, incremented on each request as the current size of the
	// pending queue.
	CumulativePendingQueue uint64
}

A NFSTransportStats contains statistics for the NFS mount RPC requests and responses.

type Namespace

type Namespace struct {
	Type  string // Namespace type.
	Inode uint32 // Inode number of the namespace. If two processes are in the same namespace their inodes will match.
}

Namespace represents a single namespace of a process.

type Namespaces

type Namespaces map[string]Namespace

Namespaces contains all of the namespaces that the process is contained in.

type NetDev

type NetDev map[string]NetDevLine

NetDev is parsed from /proc/net/dev or /proc/[pid]/net/dev. The map keys are interface names.

func (NetDev) Total

func (netDev NetDev) Total() NetDevLine

Total aggregates the values across interfaces and returns a new NetDevLine. The Name field will be a sorted comma separated list of interface names.

type NetDevLine

type NetDevLine struct {
	Name         string `json:"name"`          // The name of the interface.
	RxBytes      uint64 `json:"rx_bytes"`      // Cumulative count of bytes received.
	RxPackets    uint64 `json:"rx_packets"`    // Cumulative count of packets received.
	RxErrors     uint64 `json:"rx_errors"`     // Cumulative count of receive errors encountered.
	RxDropped    uint64 `json:"rx_dropped"`    // Cumulative count of packets dropped while receiving.
	RxFIFO       uint64 `json:"rx_fifo"`       // Cumulative count of FIFO buffer errors.
	RxFrame      uint64 `json:"rx_frame"`      // Cumulative count of packet framing errors.
	RxCompressed uint64 `json:"rx_compressed"` // Cumulative count of compressed packets received by the device driver.
	RxMulticast  uint64 `json:"rx_multicast"`  // Cumulative count of multicast frames received by the device driver.
	TxBytes      uint64 `json:"tx_bytes"`      // Cumulative count of bytes transmitted.
	TxPackets    uint64 `json:"tx_packets"`    // Cumulative count of packets transmitted.
	TxErrors     uint64 `json:"tx_errors"`     // Cumulative count of transmit errors encountered.
	TxDropped    uint64 `json:"tx_dropped"`    // Cumulative count of packets dropped while transmitting.
	TxFIFO       uint64 `json:"tx_fifo"`       // Cumulative count of FIFO buffer errors.
	TxCollisions uint64 `json:"tx_collisions"` // Cumulative count of collisions detected on the interface.
	TxCarrier    uint64 `json:"tx_carrier"`    // Cumulative count of carrier losses detected by the device driver.
	TxCompressed uint64 `json:"tx_compressed"` // Cumulative count of compressed packets transmitted by the device driver.
}

NetDevLine is single line parsed from /proc/net/dev or /proc/[pid]/net/dev.

type NetUnix

type NetUnix struct {
	Rows []*NetUnixLine
}

NetUnix holds the data read from /proc/net/unix.

func NewNetUnix

func NewNetUnix() (*NetUnix, error)

NewNetUnix returns data read from /proc/net/unix.

func NewNetUnixByPath

func NewNetUnixByPath(path string) (*NetUnix, error)

NewNetUnixByPath returns data read from /proc/net/unix by file path. It might returns an error with partial parsed data, if an error occur after some data parsed.

func NewNetUnixByReader

func NewNetUnixByReader(reader io.Reader) (*NetUnix, error)

NewNetUnixByReader returns data read from /proc/net/unix by a reader. It might returns an error with partial parsed data, if an error occur after some data parsed.

type NetUnixFlags

type NetUnixFlags uint64

NetUnixFlags is the type of the flags field.

func (NetUnixFlags) String

func (f NetUnixFlags) String() string

type NetUnixLine

type NetUnixLine struct {
	KernelPtr string
	RefCount  uint64
	Protocol  uint64
	Flags     NetUnixFlags
	Type      NetUnixType
	State     NetUnixState
	Inode     uint64
	Path      string
}

NetUnixLine represents a line of /proc/net/unix.

type NetUnixState

type NetUnixState uint64

NetUnixState is the type of the state field.

func (NetUnixState) String

func (s NetUnixState) String() string

type NetUnixType

type NetUnixType uint64

NetUnixType is the type of the type field.

func (NetUnixType) String

func (t NetUnixType) String() string

type PSILine

type PSILine struct {
	Avg10  float64
	Avg60  float64
	Avg300 float64
	Total  uint64
}

PSILine is a single line of values as returned by /proc/pressure/* The Avg entries are averages over n seconds, as a percentage The Total line is in microseconds

type PSIStats

type PSIStats struct {
	Some *PSILine
	Full *PSILine
}

PSIStats represent pressure stall information from /proc/pressure/* Some indicates the share of time in which at least some tasks are stalled Full indicates the share of time in which all non-idle tasks are stalled simultaneously

type Proc

type Proc struct {
	// The process ID.
	PID int
	// contains filtered or unexported fields
}

Proc provides information about a running process.

func NewProc

func NewProc(pid int) (Proc, error)

NewProc returns a process for the given pid under /proc.

func Self

func Self() (Proc, error)

Self returns a process for the current process read via /proc/self.

func (Proc) CmdLine

func (p Proc) CmdLine() ([]string, error)

CmdLine returns the command line of a process.

func (Proc) Comm

func (p Proc) Comm() (string, error)

Comm returns the command name of a process.

func (Proc) Cwd

func (p Proc) Cwd() (string, error)

Cwd returns the absolute path to the current working directory of the process.

func (Proc) Executable

func (p Proc) Executable() (string, error)

Executable returns the absolute path of the executable command of a process.

func (Proc) FileDescriptorTargets

func (p Proc) FileDescriptorTargets() ([]string, error)

FileDescriptorTargets returns the targets of all file descriptors of a process. If a file descriptor is not a symlink to a file (like a socket), that value will be the empty string.

func (Proc) FileDescriptors

func (p Proc) FileDescriptors() ([]uintptr, error)

FileDescriptors returns the currently open file descriptors of a process.

func (Proc) FileDescriptorsLen

func (p Proc) FileDescriptorsLen() (int, error)

FileDescriptorsLen returns the number of currently open file descriptors of a process.

func (Proc) IO added in v0.0.2

func (p Proc) IO() (ProcIO, error)

IO creates a new ProcIO instance from a given Proc instance.

func (Proc) Limits added in v0.0.2

func (p Proc) Limits() (ProcLimits, error)

Limits returns the current soft limits of the process.

func (Proc) MountStats

func (p Proc) MountStats() ([]*Mount, error)

MountStats retrieves statistics and configuration for mount points in a process's namespace.

func (Proc) Namespaces added in v0.0.2

func (p Proc) Namespaces() (Namespaces, error)

Namespaces reads from /proc/<pid>/ns/* to get the namespaces of which the process is a member.

func (Proc) NetDev added in v0.0.2

func (p Proc) NetDev() (NetDev, error)

NetDev returns kernel/system statistics read from /proc/[pid]/net/dev.

func (Proc) NewLimits deprecated

func (p Proc) NewLimits() (ProcLimits, error)

NewLimits returns the current soft limits of the process.

Deprecated: use p.Limits() instead

func (Proc) NewStat deprecated

func (p Proc) NewStat() (ProcStat, error)

NewStat returns the current status information of the process.

Deprecated: use NewStat() instead

func (Proc) NewStatus

func (p Proc) NewStatus() (ProcStatus, error)

NewStatus returns the current status information of the process.

func (Proc) RootDir

func (p Proc) RootDir() (string, error)

RootDir returns the absolute path to the process's root directory (as set by chroot)

func (Proc) Stat added in v0.0.2

func (p Proc) Stat() (ProcStat, error)

Stat returns the current status information of the process.

type ProcIO

type ProcIO struct {
	// Chars read.
	RChar uint64
	// Chars written.
	WChar uint64
	// Read syscalls.
	SyscR uint64
	// Write syscalls.
	SyscW uint64
	// Bytes read.
	ReadBytes uint64
	// Bytes written.
	WriteBytes uint64
	// Bytes written, but taking into account truncation. See
	// Documentation/filesystems/proc.txt in the kernel sources for
	// detailed explanation.
	CancelledWriteBytes int64
}

ProcIO models the content of /proc/<pid>/io.

type ProcLimits

type ProcLimits struct {
	// CPU time limit in seconds.
	CPUTime int64
	// Maximum size of files that the process may create.
	FileSize int64
	// Maximum size of the process's data segment (initialized data,
	// uninitialized data, and heap).
	DataSize int64
	// Maximum size of the process stack in bytes.
	StackSize int64
	// Maximum size of a core file.
	CoreFileSize int64
	// Limit of the process's resident set in pages.
	ResidentSet int64
	// Maximum number of processes that can be created for the real user ID of
	// the calling process.
	Processes int64
	// Value one greater than the maximum file descriptor number that can be
	// opened by this process.
	OpenFiles int64
	// Maximum number of bytes of memory that may be locked into RAM.
	LockedMemory int64
	// Maximum size of the process's virtual memory address space in bytes.
	AddressSpace int64
	// Limit on the combined number of flock(2) locks and fcntl(2) leases that
	// this process may establish.
	FileLocks int64
	// Limit of signals that may be queued for the real user ID of the calling
	// process.
	PendingSignals int64
	// Limit on the number of bytes that can be allocated for POSIX message
	// queues for the real user ID of the calling process.
	MsqqueueSize int64
	// Limit of the nice priority set using setpriority(2) or nice(2).
	NicePriority int64
	// Limit of the real-time priority set using sched_setscheduler(2) or
	// sched_setparam(2).
	RealtimePriority int64
	// Limit (in microseconds) on the amount of CPU time that a process
	// scheduled under a real-time scheduling policy may consume without making
	// a blocking system call.
	RealtimeTimeout int64
}

ProcLimits represents the soft limits for each of the process's resource limits. For more information see getrlimit(2): http://man7.org/linux/man-pages/man2/getrlimit.2.html.

type ProcStat

type ProcStat struct {
	// The process ID.
	PID int
	// The filename of the executable.
	Comm string
	// The process state.
	State string
	// The PID of the parent of this process.
	PPID int
	// The process group ID of the process.
	PGRP int
	// The session ID of the process.
	Session int
	// The controlling terminal of the process.
	TTY int
	// The ID of the foreground process group of the controlling terminal of
	// the process.
	TPGID int
	// The kernel flags word of the process.
	Flags uint
	// The number of minor faults the process has made which have not required
	// loading a memory page from disk.
	MinFlt uint
	// The number of minor faults that the process's waited-for children have
	// made.
	CMinFlt uint
	// The number of major faults the process has made which have required
	// loading a memory page from disk.
	MajFlt uint
	// The number of major faults that the process's waited-for children have
	// made.
	CMajFlt uint
	// Amount of time that this process has been scheduled in user mode,
	// measured in clock ticks.
	UTime uint
	// Amount of time that this process has been scheduled in kernel mode,
	// measured in clock ticks.
	STime uint
	// Amount of time that this process's waited-for children have been
	// scheduled in user mode, measured in clock ticks.
	CUTime uint
	// Amount of time that this process's waited-for children have been
	// scheduled in kernel mode, measured in clock ticks.
	CSTime uint
	// For processes running a real-time scheduling policy, this is the negated
	// scheduling priority, minus one.
	Priority int
	// The nice value, a value in the range 19 (low priority) to -20 (high
	// priority).
	Nice int
	// Number of threads in this process.
	NumThreads int
	// The time the process started after system boot, the value is expressed
	// in clock ticks.
	Starttime uint64
	// Virtual memory size in bytes.
	VSize uint
	// Resident set size in pages.
	RSS int
	// contains filtered or unexported fields
}

ProcStat provides status information about the process, read from /proc/[pid]/stat.

func (ProcStat) CPUTime

func (s ProcStat) CPUTime() float64

CPUTime returns the total CPU user and system time in seconds.

func (ProcStat) ResidentMemory

func (s ProcStat) ResidentMemory() int

ResidentMemory returns the resident memory size in bytes.

func (ProcStat) StartTime

func (s ProcStat) StartTime() (float64, error)

StartTime returns the unix timestamp of the process in seconds.

func (ProcStat) VirtualMemory

func (s ProcStat) VirtualMemory() uint

VirtualMemory returns the virtual memory size in bytes.

type ProcStatus

type ProcStatus struct {
	// The process ID.
	PID int
	// The process name.
	Name string

	// Peak virtual memory size.
	VmPeak uint64
	// Virtual memory size.
	VmSize uint64
	// Locked memory size.
	VmLck uint64
	// Pinned memory size.
	VmPin uint64
	// Peak resident set size.
	VmHWM uint64
	// Resident set size (sum of RssAnnon RssFile and RssShmem).
	VmRSS uint64
	// Size of resident anonymous memory.
	RssAnon uint64
	// Size of resident file mappings.
	RssFile uint64
	// Size of resident shared memory.
	RssShmem uint64
	// Size of data segments.
	VmData uint64
	// Size of stack segments.
	VmStk uint64
	// Size of text segments.
	VmExe uint64
	// Shared library code size.
	VmLib uint64
	// Page table entries size.
	VmPTE uint64
	// Size of second-level page tables.
	VmPMD uint64
	// Swapped-out virtual memory size by anonymous private.
	VmSwap uint64
	// Size of hugetlb memory portions
	HugetlbPages uint64

	// Number of voluntary context switches.
	VoluntaryCtxtSwitches uint64
	// Number of involuntary context switches.
	NonVoluntaryCtxtSwitches uint64
}

ProcStat provides status information about the process, read from /proc/[pid]/stat.

func (ProcStatus) TotalCtxtSwitches

func (s ProcStatus) TotalCtxtSwitches() uint64

TotalCtxtSwitches returns the total context switch.

type Procs

type Procs []Proc

Procs represents a list of Proc structs.

func AllProcs

func AllProcs() (Procs, error)

AllProcs returns a list of all currently available processes under /proc.

func (Procs) Len

func (p Procs) Len() int

func (Procs) Less

func (p Procs) Less(i, j int) bool

func (Procs) Swap

func (p Procs) Swap(i, j int)

type SoftIRQStat

type SoftIRQStat struct {
	Hi          uint64
	Timer       uint64
	NetTx       uint64
	NetRx       uint64
	Block       uint64
	BlockIoPoll uint64
	Tasklet     uint64
	Sched       uint64
	Hrtimer     uint64
	Rcu         uint64
}

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 Stat

type Stat struct {
	// Boot time in seconds since the Epoch.
	BootTime uint64
	// Summed up cpu statistics.
	CPUTotal CPUStat
	// Per-CPU statistics.
	CPU []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
}

Stat represents kernel/system statistics.

func NewStat deprecated

func NewStat() (Stat, error)

NewStat returns information about current cpu/process statistics. See https://www.kernel.org/doc/Documentation/filesystems/proc.txt

Deprecated: use fs.Stat() instead

type XfrmStat

type XfrmStat struct {
	// All errors which are not matched by other
	XfrmInError int
	// No buffer is left
	XfrmInBufferError int
	// Header Error
	XfrmInHdrError int
	// No state found
	// i.e. either inbound SPI, address, or IPSEC protocol at SA is wrong
	XfrmInNoStates int
	// Transformation protocol specific error
	// e.g. SA Key is wrong
	XfrmInStateProtoError int
	// Transformation mode specific error
	XfrmInStateModeError int
	// Sequence error
	// e.g. sequence number is out of window
	XfrmInStateSeqError int
	// State is expired
	XfrmInStateExpired int
	// State has mismatch option
	// e.g. UDP encapsulation type is mismatched
	XfrmInStateMismatch int
	// State is invalid
	XfrmInStateInvalid int
	// No matching template for states
	// e.g. Inbound SAs are correct but SP rule is wrong
	XfrmInTmplMismatch int
	// No policy is found for states
	// e.g. Inbound SAs are correct but no SP is found
	XfrmInNoPols int
	// Policy discards
	XfrmInPolBlock int
	// Policy error
	XfrmInPolError int
	// All errors which are not matched by others
	XfrmOutError int
	// Bundle generation error
	XfrmOutBundleGenError int
	// Bundle check error
	XfrmOutBundleCheckError int
	// No state was found
	XfrmOutNoStates int
	// Transformation protocol specific error
	XfrmOutStateProtoError int
	// Transportation mode specific error
	XfrmOutStateModeError int
	// Sequence error
	// i.e sequence number overflow
	XfrmOutStateSeqError int
	// State is expired
	XfrmOutStateExpired int
	// Policy discads
	XfrmOutPolBlock int
	// Policy is dead
	XfrmOutPolDead int
	// Policy Error
	XfrmOutPolError     int
	XfrmFwdHdrError     int
	XfrmOutStateInvalid int
	XfrmAcquireError    int
}

XfrmStat models the contents of /proc/net/xfrm_stat.

func NewXfrmStat

func NewXfrmStat() (XfrmStat, error)

NewXfrmStat reads the xfrm_stat statistics.

Directories

Path Synopsis
Package bcache provides access to statistics exposed by the bcache (Linux block cache).
Package bcache provides access to statistics exposed by the bcache (Linux block cache).
internal
fs
Package nfs implements parsing of /proc/net/rpc/nfsd.
Package nfs implements parsing of /proc/net/rpc/nfsd.
Package sysfs provides functions to retrieve system and kernel metrics from the pseudo-filesystem sys.
Package sysfs provides functions to retrieve system and kernel metrics from the pseudo-filesystem sys.
Package xfs provides access to statistics exposed by the XFS filesystem.
Package xfs provides access to statistics exposed by the XFS filesystem.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL