procfs

package module
v0.0.0-...-eaec67b Latest Latest
Warning

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

Go to latest
Published: Aug 16, 2016 License: Apache-2.0 Imports: 15 Imported by: 25

README

ProcFS

GoDoc Build Status

Golang library to parse the =/proc= file system on Linux machines.

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.

Status

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/acksin/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 = "/proc"

DefaultMountPoint is the common mount point of the proc filesystem.

Variables

This section is empty.

Functions

This section is empty.

Types

type DiskstatLine

type DiskstatLine struct {
	// 1 - major number
	MajorVersion int64
	// 2 - minor mumber
	MinorNumber int64
	// 3 - device name
	DeviceName int64
	// 4 - reads completed successfully
	ReadsCompleted int64
	// 5 - reads merged
	ReadsMerged int64
	// 6 - sectors read
	SectorsRead int64
	// 7 - time spent reading (ms)
	TimeSpentReading int64
	// 8 - writes completed
	WritesCompleted int64
	// 9 - writes merged
	WritesMerged int64
	// 10 - sectors written
	SectorsWritten int64
	// 11 - time spent writing (ms)
	TimeSpentWriting int64
	// 12 - I/Os currently in progress
	IOInProgress int64
	// 13 - time spent doing I/Os (ms)
	TimeDoingIO int64
	// 14 - weighted time spent doing I/Os (ms)
	WeightedTimeDoingIO int64
}

type Diskstats

type Diskstats []DiskstatLine

func NewDiskstats

func NewDiskstats() (Diskstats, error)

type FDs

type FDs map[string]string

ProcFD models the content of /proc/<pid>/fd/<fd>.

type FS

type FS string

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

func NewFS

func NewFS(mountPoint string) (FS, error)

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

func (FS) AllProcs

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

AllProcs returns a list of all currently available processes.

func (FS) NewDiskstats

func (fs FS) NewDiskstats() (m Diskstats, err error)

NewDiskstats returns an information about current kernel/system statistics.

func (FS) NewIPVSBackendStatus

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

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

func (FS) NewIPVSStats

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

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

func (FS) NewMeminfo

func (fs FS) NewMeminfo() (m Meminfo, err error)

NewMeminfo returns an information about current kernel/system statistics.

func (FS) NewNetSockstat

func (fs FS) NewNetSockstat() (m NetSockstat, err error)

NewNetSockstat returns an information about current kernel/system statistics.

func (FS) NewNetTCP

func (fs FS) NewNetTCP() (m NetTCP, err error)

NewNetTCP returns an information about current kernel/system statistics.

func (FS) NewProc

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

NewProc returns a process for the given pid.

func (FS) NewStat

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

NewStat returns an information about current kernel/system statistics.

func (FS) NewSys

func (fs FS) NewSys() (m Sys, err error)

func (FS) ParseMDStat

func (fs FS) ParseMDStat() (mdstates []MDStat, err error)

ParseMDStat parses an mdstat-file and returns a struct with the relevant infos.

func (FS) Path

func (fs FS) Path(p ...string) string

Path returns the path of the given subsystem relative to the procfs root.

func (FS) Self

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

Self returns a process for the current process.

type IPVSBackendStatus

type IPVSBackendStatus struct {
	// The local (virtual) IP address.
	LocalAddress net.IP
	// The local (virtual) port.
	LocalPort uint16
	// The transport protocol (TCP, UDP).
	Proto string
	// The remote (real) IP address.
	RemoteAddress net.IP
	// The remote (real) port.
	RemotePort uint16
	// 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.

func NewIPVSBackendStatus

func NewIPVSBackendStatus() ([]IPVSBackendStatus, error)

NewIPVSBackendStatus reads and returns the status of all (virtual,real) server pairs.

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`.

func NewIPVSStats

func NewIPVSStats() (IPVSStats, error)

NewIPVSStats reads the IPVS statistics.

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 Meminfo

type Meminfo struct {
	// Total usable ram (i.e. physical ram minus a few reserved
	// bits and the kernel binary code)
	MemTotal int64 `meminfo:"MemTotal"`
	// The sum of LowFree+HighFree
	MemFree int64 `meminfo:"MemFree"`
	// An estimate of how much memory is available for starting
	// new applications, without swapping. Calculated from
	// MemFree, SReclaimable, the size of the file LRU lists, and
	// the low watermarks in each zone.  The estimate takes into
	// account that the system needs some page cache to function
	// well, and that not all reclaimable slab will be
	// reclaimable, due to items being in use. The impact of those
	// factors will vary from system to system.
	MemAvailable int64 `meminfo:"MemAvailable"`
	// Relatively temporary storage for raw disk blocks shouldn't
	// get tremendously large (20MB or so)
	Buffers int64 `meminfo:"Buffers"`
	Cached  int64 `meminfo:"Cached"`
	// SwapCached is the current amount of swap space used as a
	// cache.
	SwapCached int64 `meminfo:"SwapCached"`
	// Memory that has been used more recently and usually not
	// reclaimed unless absolutely necessary.
	Active int64 `meminfo:"Active"`
	// Memory which has been less recently used.  It is more
	// eligible to be reclaimed for other purposes
	Inactive     int64 `meminfo:"Inactive"`
	ActiveAnon   int64 `meminfo:"Active(anon)"`
	InactiveAnon int64 `meminfo:"Inactive(anon)"`
	ActiveFile   int64 `meminfo:"Active(file)"`
	InactiveFile int64 `meminfo:"Inactive(file)"`
	Unevictable  int64 `meminfo:"Unevictable"`
	Mlocked      int64 `meminfo:"Mlocked"`
	// total amount of swap space available
	SwapTotal int64 `meminfo:"SwapTotal"`
	// SwapFree is the total amount of swap space free.
	SwapFree int64 `meminfo:"SwapFree"`
	// Memory which is waiting to get written back to the disk
	Dirty int64 `meminfo:"Dirty"`
	// Memory which is actively being written back to the disk
	Writeback int64 `meminfo:"Writeback"`
	// Non-file backed pages mapped into userspace page tables
	AnonPages int64 `meminfo:"AnonPages"`
	// files which have been mmaped, such as libraries
	Mapped int64 `meminfo:"Mapped"`
	Shmem  int64 `meminfo:"Shmem"`
	// in-kernel data structures cache
	Slab int64 `meminfo:"Slab"`
	// Part of Slab, that might be reclaimed, such as caches
	SReclaimable int64 `meminfo:"SReclaimable"`
	// Part of Slab, that cannot be reclaimed on memory pressure
	SUnreclaim  int64 `meminfo:"SUnreclaim"`
	KernelStack int64 `meminfo:"KernelStack"`
	// amount of memory dedicated to the lowest level of page
	// tables.
	PageTables int64 `meminfo:"PageTables"`
	// NFS pages sent to the server, but not yet committed to
	// stable storage
	NFSUnstable int64 `meminfo:"NFS_Unstable"`
	// Memory used for block device "bounce buffers"
	Bounce int64 `meminfo:"Bounce"`
	// Memory used by FUSE for temporary writeback buffers
	WritebackTmp int64 `meminfo:"WritebackTmp"`
	// Based on the overcommit ratio ('vm.overcommit_ratio'),
	// this is the total amount of  memory currently available to
	// be allocated on the system. This limit is only adhered to
	// if strict overcommit accounting is enabled (mode 2 in
	// 'vm.overcommit_memory').
	// The CommitLimit is calculated with the following formula:
	// CommitLimit = ([total RAM pages] - [total huge TLB pages]) *
	//                overcommit_ratio / 100 + [total swap pages]
	// For example, on a system with 1G of physical RAM and 7G
	// of swap with a `vm.overcommit_ratio` of 30 it would
	// yield a CommitLimit of 7.3G.
	// For more details, see the memory overcommit documentation
	// in vm/overcommit-accounting.
	CommitLimit int64 `meminfo:"CommitLimit"`
	// The amount of memory presently allocated on the system.
	// The committed memory is a sum of all of the memory which
	// has been allocated by processes, even if it has not been
	// "used" by them as of yet. A process which malloc()'s 1G
	// of memory, but only touches 300M of it will show up as
	// using 1G. This 1G is memory which has been "committed" to
	// by the VM and can be used at any time by the allocating
	// application. With strict overcommit enabled on the system
	// (mode 2 in 'vm.overcommit_memory'),allocations which would
	// exceed the CommitLimit (detailed above) will not be permitted.
	// This is useful if one needs to guarantee that processes will
	// not fail due to lack of memory once that memory has been
	// successfully allocated.
	CommittedAS int64 `meminfo:"Committed_AS"`
	// total size of vmalloc memory area
	VMallocTotal int64 `meminfo:"VmallocTotal"`
	// amount of vmalloc area which is used
	VMallocUsed int64 `meminfo:"VmallocUsed"`
	// largest contiguous block of vmalloc area which is free
	VMallocChunk      int64 `meminfo:"VmallocChunk"`
	HardwareCorrupted int64 `meminfo:"HardwareCorrupted"`
	AnonHugePages     int64 `meminfo:"AnonHugePages"`
	HugePagesTotal    int64 `meminfo:"HugePages_Total"`
	HugePagesFree     int64 `meminfo:"HugePages_Free"`
	HugePagesRsvd     int64 `meminfo:"HugePages_Rsvd"`
	HugePagesSurp     int64 `meminfo:"HugePages_Surp"`
	Hugepagesize      int64 `meminfo:"Hugepagesize"`
	DirectMap4k       int64 `meminfo:"DirectMap4k"`
	DirectMap2M       int64 `meminfo:"DirectMap2M"`
}

Meminfo represents memory statistics.

func NewMeminfo

func NewMeminfo() (Meminfo, error)

NewMeminfo returns kernel/system statistics read from /proc/stat.

type NetSockstat

type NetSockstat struct {
	Sockets struct {
		Used int64
	}

	TCP struct {
		InUse  int64
		Orphan int64
		Tw     int64
		Alloc  int64
		Mem    int64
	}

	UDP struct {
		InUse int64
		Mem   int64
	}

	UDPLite struct {
		InUse int64
	}

	RAW struct {
		InUse int64
	}

	FRAG struct {
		InUse  int64
		Memory int64
	}
}

NetSockstat stats on /proc/net/sockstat

func NewNetSockstat

func NewNetSockstat() (NetSockstat, error)

NewNetSockstat returns kernel/system statistics read from /proc/net/sockstat.

type NetTCP

type NetTCP []NetTCPLine

NetTCP stats on /proc/net/tcp

func NewNetTCP

func NewNetTCP() (NetTCP, error)

NewNetTCP returns kernel/system statistics read from /proc/net/tcp.

type NetTCPLine

type NetTCPLine struct {
	Sl            string `net_tcp:"sl"`
	LocalAddress  string `net_tcp:"local_address"`
	RemoteAddress string `net_tcp:"rem_address"`
	St            string `net_tcp:"st"`
	TxQueue       string `net_tcp:"tx_queue"`
	RxQueue       string `net_tcp:"rx_queue"`
	Tr            string `net_tcp:"tr"`
	TmWhen        string `net_tcp:"tm->when"`
	Retrnsmt      string `net_tcp:"retrnsmt"`
	UID           string `net_tcp:"uid"`
	Timeout       string `net_tcp:"timeout"`
	Inode         string `net_tcp:"inode"`
	RefCount      string `net_tcp:""`
	MemoryAddress string `net_tcp:""`
}

NetTCPLine is a parsed line of /proc/net/tcp

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

func (p Proc) NewFD() (FDs, error)

NewFD creates a new ProcFD instance from a given Proc instance.

func (Proc) NewIO

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

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

func (Proc) NewLimits

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

NewLimits returns the current soft limits of the process.

func (Proc) NewStat

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

NewStat returns the current status information of the process.

func (Proc) NewStatus

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

NewStatus 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 int
	// Maximum size of files that the process may create.
	FileSize int
	// Maximum size of the process's data segment (initialized data,
	// uninitialized data, and heap).
	DataSize int
	// Maximum size of the process stack in bytes.
	StackSize int
	// Maximum size of a core file.
	CoreFileSize int
	// Limit of the process's resident set in pages.
	ResidentSet int
	// Maximum number of processes that can be created for the real user ID of
	// the calling process.
	Processes int
	// Value one greater than the maximum file descriptor number that can be
	// opened by this process.
	OpenFiles int
	// Maximum number of bytes of memory that may be locked into RAM.
	LockedMemory int
	// Maximum size of the process's virtual memory address space in bytes.
	AddressSpace int
	// Limit on the combined number of flock(2) locks and fcntl(2) leases that
	// this process may establish.
	FileLocks int
	// Limit of signals that may be queued for the real user ID of the calling
	// process.
	PendingSignals int
	// Limit on the number of bytes that can be allocated for POSIX message
	// queues for the real user ID of the calling process.
	MsqqueueSize int
	// Limit of the nice priority set using setpriority(2) or nice(2).
	NicePriority int
	// Limit of the real-time priority set using sched_setscheduler(2) or
	// sched_setparam(2).
	RealtimePriority int
	// 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 int
}

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 int
	// 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() int

VirtualMemory returns the virtual memory size in bytes.

type ProcStatus

type ProcStatus struct {
	Name                     string `proc_status:"Name"`
	State                    string `proc_status:"State"`
	Tgid                     string `proc_status:"Tgid"`
	Ngid                     string `proc_status:"Ngid"`
	Pid                      string `proc_status:"Pid"`
	PPid                     string `proc_status:"PPid"`
	TracerPid                string `proc_status:"TracerPid"`
	UID                      string `proc_status:"Uid"`
	GID                      string `proc_status:"Gid"`
	FDSize                   string `proc_status:"FDSize"`
	Groups                   string `proc_status:"Groups"`
	VMPeak                   string `proc_status:"VmPeak"`
	VMSize                   string `proc_status:"VmSize"`
	VMLck                    string `proc_status:"VmLck"`
	VMPin                    string `proc_status:"VmPin"`
	VMHWM                    string `proc_status:"VmHWM"`
	VMRSS                    string `proc_status:"VmRSS"`
	VMData                   string `proc_status:"VmData"`
	VMStk                    string `proc_status:"VmStk"`
	VMExe                    string `proc_status:"VmExe"`
	VMLib                    string `proc_status:"VmLib"`
	VMPTE                    string `proc_status:"VmPTE"`
	VMSwap                   string `proc_status:"VmSwap"`
	Threads                  string `proc_status:"Threads"`
	SigQ                     string `proc_status:"SigQ"`
	SigPnd                   string `proc_status:"SigPnd"`
	ShdPnd                   string `proc_status:"ShdPnd"`
	SigBlk                   string `proc_status:"SigBlk"`
	SigIgn                   string `proc_status:"SigIgn"`
	SigCgt                   string `proc_status:"SigCgt"`
	CapInh                   string `proc_status:"CapInh"`
	CapPrm                   string `proc_status:"CapPrm"`
	CapEff                   string `proc_status:"CapEff"`
	CapBnd                   string `proc_status:"CapBnd"`
	Seccomp                  string `proc_status:"Seccomp"`
	CpusAllowed              string `proc_status:"Cpus_allowed"`
	CpusAllowedList          string `proc_status:"Cpus_allowed_list"`
	MemsAllowed              string `proc_status:"Mems_allowed"`
	MemsAllowedList          string `proc_status:"Mems_allowed_list"`
	VoluntaryCtxtSwitches    string `proc_status:"voluntary_ctxt_switches"`
	NonvoluntaryCtxtSwitches string `proc_status:"nonvoluntary_ctxt_switches"`
	// contains filtered or unexported fields
}

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 Stat

type Stat struct {
	// Boot time in seconds since the Epoch.
	BootTime int64
}

Stat represents kernel/system statistics.

func NewStat

func NewStat() (Stat, error)

NewStat returns kernel/system statistics read from /proc/stat.

type Sys

type Sys map[string]string

func NewSys

func NewSys() (Sys, error)

Jump to

Keyboard shortcuts

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