go-sysinfo is a library for collecting system information.

Overview

go-sysinfo

Build Status Go Documentation

go-sysinfo is a library for collecting system information. This includes information about the host machine and processes running on the host.

The available features vary based on what has been implemented by the "provider" for the operating system. At runtime you check to see if additional interfaces are implemented by the returned Host or Process. For example:

process, err := sysinfo.Self()
if err != nil {
	return err
}

if handleCounter, ok := process.(types.OpenHandleCounter); ok {
	count, err := handleCounter.OpenHandleCount()
	if err != nil {
		return err
	}
	log.Printf("%d open handles", count)
}

These tables show what methods are implemented as well as the extra interfaces that are implemented.

Host Features Darwin Linux Windows AIX/ppc64
Info() x x x x
Memory() x x x x
CPUTimer x x x x
VMStat x
NetworkCounters x
Process Features Darwin Linux Windows AIX/ppc64
Info() x x x x
Memory() x x x x
User() x x x x
Parent() x x x x
CPUTimer x x x x
Environment x x x
OpenHandleEnumerator x
OpenHandleCounter x
Seccomp x
Capabilities x
Comments
  • package broken/ won't build

    package broken/ won't build

    I use Go agent for elastic apm but and go-sysinfo is one of the dependency there but since this morning I am getting this error while trying to build my packages

    github.com/elastic/go-sysinfo/providers/linux
    src/github.com/elastic/go-sysinfo/providers/linux/host_linux.go:45:20: cannot convert filepath.Join(hostFS, procfs.DefaultMountPoint) (type string) to type procfs.FS
    src/github.com/elastic/go-sysinfo/providers/linux/host_linux.go:64:42: h.procFS.Path undefined (type procfs.FS has no field or method Path)
    src/github.com/elastic/go-sysinfo/providers/linux/process_linux.go:91:13: p.fs.Path undefined (type procfs.FS has no field or method Path)
    

    help?

    opened by spl0i7 13
  • all: add AIX provider

    all: add AIX provider

    Add a implementation without CGO for AIX. Host information are retrieved using AIX commands (uname, oslevel) Process information are retrieved by /proc folder.

    A CGO implementation could be added to more accurate syscalls and libraries (getprocs, libperfstat, etc). But github.com/elastic/gosigar provides such things.

    A few features are still missing:

    • Host CPU usage since boot time: there is no easy way to retrieve it.
    • Process' environment
    opened by Helflym 9
  • Containerized value showing false positive

    Containerized value showing false positive

    I'm seeing some false positives from the containerized value. This was captured while running the beat as a service.

    {
      "level": "info",
      "timestamp": "2018-04-06T21:33:35.738Z",
      "logger": "beat",
      "caller": "instance/beat.go:722",
      "message": "Host info",
      "system_info": {
        "host": {
          "architecture": "x86_64",
          "boot_time": "2018-04-06T21:31:48Z",
          "containerized": true,
          "hostname": "localhost.localdomain",
          "ips": [
            "127.0.0.1/8",
            "::1/128",
            "10.0.2.15/24",
            "fe80::a00:27ff:feaf:8570/64",
            "192.168.33.78/24",
            "fe80::a00:27ff:fe8c:2fcb/64"
          ],
          "kernel_version": "4.9.17-8.31.amzn1.x86_64",
          "mac_addresses": [
            "08:00:27:af:85:70",
            "08:00:27:8c:2f:cb"
          ],
          "os": {
            "family": "",
            "platform": "amzn",
            "name": "Amazon Linux AMI",
            "version": "2017.03",
            "major": 2017,
            "minor": 3,
            "patch": 0
          },
          "timezone": "UTC",
          "timezone_offset_sec": 0
        }
      }
    }
    {"level":"info","timestamp":"2018-04-06T23:33:32.708+0200","logger":"beat","caller":"instance/beat.go:751","message":"Process info","system_info":{"process":{"capabilities":{"inheritable":null,"permitted":["chown","dac_override","dac_read_search","fowner","fsetid","kill","setgid","setuid","setpcap","linux_immutable","net_bind_service","net_broadcast","net_admin","net_raw","ipc_lock","ipc_owner","sys_module","sys_rawio","sys_chroot","sys_ptrace","sys_pacct","sys_admin","sys_boot","sys_nice","sys_resource","sys_time","sys_tty_config","mknod","lease","audit_write","audit_control","setfcap","mac_override","mac_admin","syslog","wake_alarm","block_suspend"],"effective":["chown","dac_override","dac_read_search","fowner","fsetid","kill","setgid","setuid","setpcap","linux_immutable","net_bind_service","net_broadcast","net_admin","net_raw","ipc_lock","ipc_owner","sys_module","sys_rawio","sys_chroot","sys_ptrace","sys_pacct","sys_admin","sys_boot","sys_nice","sys_resource","sys_time","sys_tty_config","mknod","lease","audit_write","audit_control","setfcap","mac_override","mac_admin","syslog","wake_alarm","block_suspend"],"bounding":["chown","dac_override","dac_read_search","fowner","fsetid","kill","setgid","setuid","setpcap","linux_immutable","net_bind_service","net_broadcast","net_admin","net_raw","ipc_lock","ipc_owner","sys_module","sys_rawio","sys_chroot","sys_ptrace","sys_pacct","sys_admin","sys_boot","sys_nice","sys_resource","sys_time","sys_tty_config","mknod","lease","audit_write","audit_control","setfcap","mac_override","mac_admin","syslog","wake_alarm","block_suspend"],"ambient":null},"cwd":"/","exe":"/usr/share/packetbeat/bin/packetbeat","name":"packetbeat","pid":4946,"ppid":1,"seccomp":{"mode":"disabled"},"start_time":"2018-04-06T23:33:32.260+0200"}}}
    
    bug 
    opened by andrewkroh 9
  • test.sh failed on MacOS and Linux (amd64)

    test.sh failed on MacOS and Linux (amd64)

    The github actions for macos failed with the below error:

    Run .ci/scripts/test.sh
    + GO111MODULE=off
    + go get -u github.com/elastic/go-licenser
    + go mod verify
    all modules verified
    + go-licenser -d
    + go run .ci/scripts/check_format.go
    Run goimports on the code.
    providers/aix/boottime_test.go
    providers/aix/defs_aix.go
    providers/darwin/arch_darwin.go
    providers/darwin/boottime_darwin.go
    providers/darwin/defs_darwin.go
    providers/darwin/host_darwin.go
    providers/darwin/kernel_darwin.go
    providers/darwin/machineid_darwin.go
    providers/darwin/memory_darwin.go
    providers/darwin/process_darwin.go
    providers/darwin/process_darwin_test.go
    providers/darwin/syscall_darwin.go
    providers/linux/os_test.go
    exit status 1
    
    opened by v1v 7
  • Add crosscompiling tests

    Add crosscompiling tests

    I got stuck by a crosscompile issue in https://github.com/elastic/beats/pull/5968 so I quickly put together these tests. So far this does not solve the problem but allows us to discuss on the potential solutions.

    1 errors occurred:
    --> darwin/386 error: exit status 2
    Stderr: # github.com/elastic/go-sysinfo/providers/darwin
    ../providers/darwin/boottime_darwin.go:28:12: undefined: sysctlByName
    ../providers/darwin/boottime_darwin.go:32:32: tv.Sec undefined (type syscall.Timeval32 has no field or method Sec)
    ../providers/darwin/boottime_darwin.go:32:47: tv.Usec undefined (type syscall.Timeval32 has no field or method Usec)
    ../providers/darwin/memory_darwin.go:25:12: undefined: sysctlByName
    
    make: *** [crosscompile] Error 1
    

    For the above I'm not sure where sysctlByName by name should be defined?

    @andrewkroh I also saw that you have a .ci folder in the repo. Would you expect gox to be executed from inside a go script in .ci/scripts?

    review 
    opened by ruflin 7
  • First pass at a Makefile

    First pass at a Makefile

    This is a first attempt at a basic makefile, with the goal being that make update should run everything that needs to be run in order for the CI to pass its initial checks.

    I don't know if I've ever seen someone use file targets to install go binaries, but it seems to work.

    I'd like to add a helptext and some kind of linter, but I'd like to get the basics squared away first.

    [zube]: In Progress 
    opened by fearful-symmetry 5
  • Return not containerized if /proc/1/cgroup does not exist

    Return not containerized if /proc/1/cgroup does not exist

    We check the contents of /proc/1/cgroup to determine if we are in a container or not. However, this pseudo file will not exist if cgroup is not available, e.g. if it has been explicitly disabled, maybe on a shared system. This PR returns false (i.e. not containerized) if the file does not exist.

    This has been reported on SO, and we fixed a similar issue in Beats (https://github.com/elastic/beats/issues/3666).

    review 
    opened by cwurm 5
  •  Unified CPUTimer interface

    Unified CPUTimer interface

    Change CPUTimer interface such that it matches Host's CPUTime signature, and modify the existing Process implementations to match.

    Also, stop swallowing errors in Process.CPUTime and Process.Memory. The latter involves also changing types.Memory's method signature to return an error.

    Closes #17 Closes #18

    opened by axw 5
  • feat: replace custom sysctl implementation with stdlib

    feat: replace custom sysctl implementation with stdlib

    Remove custom string->mib conversion code and sysctl implementation. Reduce code complexity and cgo dependency

    Related to https://github.com/elastic/apm-server/issues/8718

    opened by kruskall 3
  • ci: use orka

    ci: use orka

    Use Orka amd64 and aarch64

    It works for arm64

    image

    It fails with MacOS amd64 and also in Linux amd64, already reported in https://github.com/elastic/go-sysinfo/issues/109

    opened by v1v 3
  • Avoid reading contents when directory

    Avoid reading contents when directory

    Problem

    • An exception occurred when retrieving Memory metrics on a VM using Elastic Metric Beat.
    • As a result of investigation, when the following Directory exists, an error occurred when judging the OS.
    /etc/UPPERCASEDIR-release/
    
    • By the way, this exception did not occur in the case of the lower case Directory as shown below.
    /etc/lowercasedir-release/
    

    Cause

    • I found an error when reading a directory that starts with an uppercase letter in the following code:
    func getDistribRelease(file string) (*types.OSInfo, error) {
    	data, err := ioutil.ReadFile(file)
    ...
    

    image

    Fixes

    • Fixed not to read Directory when scanning the file used for os judgment, Directory.
    func findDistribRelease(baseDir string) (*types.OSInfo, error) {
    ...
    		info, err := os.Lstat(path)
    		if err != nil || info.Size() == 0 || info.IsDir() {
    			continue
    		}
    
    		return getDistribRelease(path)
    ...
    

    If you have a better fix, please drop or refine my Pull Request !
    Best regards.

    opened by otajisan 3
  • Darwin: non-cgo implementation

    Darwin: non-cgo implementation

    Description

    We've started relying on this library for apm-server to be able to list processes in the context of automatically running the java-attacher within the APM integration. apm-server is compiled and shipped with CGO_DISABLED=1, which is not a problem for any of the platforms except for Darwin.

    We wanted to explore improving this library to use a non-cgo implementation for darwin where we could (elastic/apm-server#8718). From my limited exploration, it seems like it's not possible to implement all the functionality provided by C calls and powered by CGO with a non-cgo implementation, however, we can still provide a new non-cgo implementation which implements most of the API and leave a few unsupported API calls that cannot be implemented returning an "unimplemented error: please use the CGO implementation" or shell out where necessary to be able to populate all the types that are fed by CGO.

    enhancement 
    opened by marclop 4
  • Linux kernel ticks assumption is error prone

    Linux kernel ticks assumption is error prone

    Problem

    The value of clock ticks (_SC_CLK_TCK) is hard coded and might varies across kernel versions and hardware platforms, it would probably be best if you could read this value dynamically. https://github.com/elastic/go-sysinfo/blob/bd131ab8b5efa45cd7e434c4b14412a253601e07/providers/linux/process_linux.go#L33

    There is an assumption here for certain conditions that might not be respected between different deployments and versions. please read the wiki article about Kernel Timer Systems:

    The original kernel timer system (called the "timer wheel) was based on incrementing a kernel-internal value (jiffies) every timer interrupt. The timer interrupt becomes the default scheduling quantum, and all other timers are based on jiffies. The timer interrupt rate (and jiffy increment rate) is defined by a compile-time constant called HZ. Different platforms use different values for HZ. Historically, the kernel used 100 as the value for HZ, yielding a jiffy interval of 10 ms. With 2.4, the HZ value for i386 was changed to 1000, yielding a jiffy interval of 1 ms. Recently (2.6.13) the kernel changed HZ for i386 to 250. (1000 was deemed too high).

    Proposed solution

    Make a sys call to retrieve the actual _SC_CLK_TCK and use it for process time calculations, the same has been done for Darwin: https://github.com/elastic/go-sysinfo/blob/f2015f14dd215ad97bd4fbe048e087945ec0223d/providers/darwin/syscall_darwin.go#L191-L194

    enhancement 
    opened by uri-weisman 3
  • LoadAverage() Where is this used?

    LoadAverage() Where is this used?

    I'm looking at using your library to provide cross-platform (Linux, BSD and Darwin) System Information, but going through the docs and codebase I don't see where .LoadAverage() is ever used or the interface.

    Is this just missing?

    bug 
    opened by prologic 3
  • Add go-sysinfo cmd

    Add go-sysinfo cmd

    Hi,

    As a new user of this package, I had to spend a little more time to understand what kind of information go-sysinfo was able to provide, say compared to other packages, e.g., https://github.com/zcalusic/sysinfo.

    A simple utility command line program would help new users to check quickly all the available information. For example, something like below.

    
    package main
    
    import (
    	"encoding/json"
    	"fmt"
    	"log"
    
    	"github.com/elastic/go-sysinfo"
    	"github.com/elastic/go-sysinfo/types"
    )
    
    type SysInfo struct {
    	ProcessInfo    types.ProcessInfo     `json:"process_info"`
    	CPUTimes       types.CPUTimes        `json:"cpu_times"`
    	MemoryInfo     types.MemoryInfo      `json:"memory_info"`
    	UserInfo       types.UserInfo        `json:"user_info"`
    	HostInfo       types.HostInfo        `json:"host_info"`
    	HostMemoryInfo *types.HostMemoryInfo `json:"host_memory_info"`
    }
    
    func GetSysInfo() SysInfo {
    	process, _ := sysinfo.Self()
    	processInfo, _ := process.Info()
    	cpuTime, _ := process.CPUTime()
    	memoryInfo, _ := process.Memory()
    	userInfo, _ := process.User()
    
    	host, _ := sysinfo.Host()
    	hostInfo := host.Info()
    	hostMemoryInfo, _ := host.Memory()
    
    	return SysInfo{
    		ProcessInfo:    processInfo,
    		CPUTimes:       cpuTime,
    		MemoryInfo:     memoryInfo,
    		UserInfo:       userInfo,
    		HostInfo:       hostInfo,
    		HostMemoryInfo: hostMemoryInfo,
    	}
    }
    
    func main() {
    	sysinf := GetSysInfo()
    
    	data, err := json.MarshalIndent(&sysinf, "", "  ")
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	fmt.Println(string(data))
    }
    
    

    Output:

    {
      "process_info": {
        "name": "sysinfo",
        "pid": 10142,
        "ppid": 25771,
        "cwd": "/workspace/go-sysinfo/cmd/sysinfo",
        "exe": "/workspace/go-sysinfo/cmd/sysinfo/sysinfo",
        "args": [
          "./sysinfo"
        ],
        "start_time": "2021-10-24T16:23:14.47Z"
      },
      "cpu_times": {
        "user": 0,
        "system": 0
      },
      "memory_info": {
        "resident_bytes": 5734400,
        "virtual_bytes": 720535552
      },
      "user_info": {
        "uid": "0",
        "euid": "0",
        "suid": "0",
        "gid": "0",
        "egid": "0",
        "sgid": "0"
      },
      "host_info": {
        "architecture": "x86_64",
        "boot_time": "2021-10-24T10:28:56Z",
        "containerized": true,
        "name": "58755aabff76",
        "ip": [
          "127.0.0.1/8",
          "172.18.0.2/16"
        ],
        "kernel_version": "5.4.72-microsoft-standard-WSL2",
        "mac": [
          "02:42:ac:12:00:02"
        ],
        "os": {
          "type": "linux",
          "family": "",
          "platform": "alpine",
          "name": "Alpine Linux",
          "version": "",
          "major": 0,
          "minor": 0,
          "patch": 0
        },
        "timezone": "UTC",
        "timezone_offset_sec": 0,
        "id": "8203ec2a7d4a85be1975970061753e5c"
      },
      "host_memory_info": {
        "total_bytes": 13293199360,
        "used_bytes": 4198158336,
        "available_bytes": 11434057728,
        "free_bytes": 9095041024,
        "virtual_total_bytes": 4294967296,
        "virtual_used_bytes": 0,
        "virtual_free_bytes": 4294967296,
        "raw": {
          "Active": 1741504512,
          "Active(anon)": 1001545728,
          "Active(file)": 739958784,
          "AnonHugePages": 262144000,
          "AnonPages": 878346240,
          "Bounce": 0,
          "Buffers": 310341632,
          "Cached": 2418610176,
          "CommitLimit": 10941566976,
          "Committed_AS": 4803932160,
          "DirectMap1G": 7516192768,
          "DirectMap2M": 6067060736,
          "DirectMap4k": 47185920,
          "Dirty": 0,
          "FileHugePages": 0,
          "FilePmdMapped": 0,
          "HugePages_Free": 0,
          "HugePages_Rsvd": 0,
          "HugePages_Surp": 0,
          "HugePages_Total": 0,
          "Hugepagesize": 2097152,
          "Hugetlb": 0,
          "Inactive": 2007437312,
          "Inactive(anon)": 297070592,
          "Inactive(file)": 1710366720,
          "KReclaimable": 216645632,
          "KernelStack": 15048704,
          "Mapped": 273330176,
          "Mlocked": 0,
          "NFS_Unstable": 0,
          "PageTables": 9781248,
          "Percpu": 6750208,
          "SReclaimable": 216645632,
          "SUnreclaim": 104050688,
          "Shmem": 386269184,
          "ShmemHugePages": 0,
          "ShmemPmdMapped": 0,
          "Slab": 320696320,
          "SwapCached": 0,
          "Unevictable": 0,
          "VmallocChunk": 0,
          "VmallocTotal": 35184372087808,
          "VmallocUsed": 35704832,
          "Writeback": 0,
          "WritebackTmp": 0
        }
      }
    }
    
    enhancement 
    opened by eozer 1
  • FreeBSD support

    FreeBSD support

    Add FreeBSD provider. When I was attempting to use this package on FreeBSD I noticed the provider was completely missing, so I implemented a provider for FreeBSD.

    Note that for the system_test.go that test's the current working directory I modified the test code to compare the inodes using os.SameFile instead of straight file comparison. The reason is that os.Getcwd() will return any path to CWD (either symlink or real path) but for any process except the calling pid (i.e. calling C.getcwd()) will return the real path and not the symlink.

    I've tested it on FreeBSD 11.2 and 12.0 using 'go test', let me know if you need anything else to be run and please feel free to leave any review comments/reject the pull request etc.

    opened by dbolcsfoldi 4
Releases(v1.8.1)
Owner
elastic
elastic
Tiny Go tool for running multiple functions concurrently and collecting their results into an error slice.

Overview Short for "ConCurrent". Tiny Go tool for running multiple functions concurrently and collecting their results into an error slice. Dependency

Nelo Mitranim 0 Nov 22, 2021
get windows system call number dynamically, it doesn't need the system call table.

GetSyscallID get windows system call number dynamically, it doesn't need the system call table. Try download go get github.com/akkuman/getsyscallid/cm

null 7 Jun 1, 2022
A program for extracting information from chrome session files.

What A tool for dumping the contents of chrome session files. Why? Most tools for reading SNSS files (chrome session files) are either broken or outda

null 39 Aug 18, 2022
A process that receives probe information and stores it in a database for reporting and analysis

probed is a process that receives probe information and stores it in a database for reporting and analysis.

Weald Technology 0 Dec 10, 2021
Otx - otx tool can scrap to find sensitive information and vulnerable endpoint urls.

otx Description This tool is base on AlienVault Open Threat Exchange (OTX)? and this tool can help you to extract all the urls endpoints which can be

ShaneKhant 3 Aug 17, 2022
utf8 - provide unicode information on runes

utf8 utf8 provides unicode code point values for input runes and the unicode rune (if printable) for a given unicode code point. With no arguments, pr

Sean Hinchee 1 Jan 8, 2022
A utility library to do files/io/bytes processing/parsing in file-system or network.

goreader A utility library to do files/io/bytes processing/parsing in file-system or network. These features are really common to be implemented for a

VOrishirne 4 Nov 1, 2021
Ento is an Entity Component System written in Go.

Ento is an Entity Component System written in Go.

Wojciech Franczyk 10 Sep 13, 2022
ptypes is a pointer-based box typing system for golang.

ptypes bypass go's type system through unsafe pointers the paradigm is to created a "boxed" type with .From and then use whatever types we want by ass

prequist 3 Aug 26, 2021
System software of computers

SSoC System software of computers BSUIR labs Project structure Client client client/components client/components/client client/components/command clie

Max Ersh 2 Jan 5, 2022
A fully Go userland with Linux bootloaders! u-root can create a one-binary root file system (initramfs) containing a busybox-like set of tools written in Go.

u-root Description u-root embodies four different projects. Go versions of many standard Linux tools, such as ls, cp, or shutdown. See cmds/core for m

null 2k Sep 23, 2022
Provides simple, semantic manipulation of the operating system's signal processing.

Provides simple, semantic manipulation of the operating system's signal processing.

Jayson Wang 0 Dec 15, 2021
Flock is a project which provides a Go solution for system level file locks for all platforms Golang supports.

Flock is a project which provides a Go solution for system level file locks for all platforms Golang supports.

Ken Sipe 0 Feb 8, 2022
This is a simple HTTP application that returns system info

sysinfo This is a simple HTTP application that returns system info. Trace Support There is also simple OpenTelemetry tracing support via the -t flag.

Evan Hazlett 1 May 22, 2022
Govalid is a data validation library that can validate most data types supported by golang

Govalid is a data validation library that can validate most data types supported by golang. Custom validators can be used where the supplied ones are not enough.

null 61 Apr 22, 2022
Maintain a lower-bitrate copy of a music library in sync with the main copy.

msync Maintain a lower-bitrate copy of your music library, in sync with the main copy.

Chris Dzombak 18 Mar 6, 2022
Golang library to act on structure fields at runtime. Similar to Python getattr(), setattr(), hasattr() APIs.

go-attr Golang library to act on structure fields at runtime. Similar to Python getattr(), setattr(), hasattr() APIs. This package provides user frien

Shyamsunder Rathi 27 Jul 5, 2022
Go library for HTTP content type negotiation

Content-Type support library for Go This library can be used to parse the value Content-Type header (if one is present) and select an acceptable media

Elviss Strazdins 42 Jul 10, 2022
A tool and library for using structural regular expressions.

Structural Regular Expressions sregx is a package and tool for using structural regular expressions as described by Rob Pike (link).

Zachary Yedidia 40 Sep 21, 2022