Collecting system metrics using Golang

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Common.go

// copy code from github.com/shirou/gopsutilpackage sysimport ("bufio""os""strings")// ReadLines reads contents from file and splits them by new line.// A convenience wrapper to ReadLinesOffsetN(filename, 0, -1).func readLines(filename string) ([]string, error) {return readLinesOffsetN(filename, 0, -1)}// ReadLines reads contents from file and splits them by new line.// The offset tells at which line number to start.// The count determines the number of lines to read (starting from offset)://   n >= 0: at most n lines//   n < 0: whole filefunc readLinesOffsetN(filename string, offset uint, n int) ([]string, error) {f, err := os.Open(filename)if err != nil {return []string{""}, err}defer f.Close()var ret []stringr := bufio.NewReader(f)for i := 0; i < n+int(offset) || n < 0; i++ {line, err := r.ReadString('\n')if err != nil {break}if i < int(offset) {continue}ret = append(ret, strings.Trim(line, "\n"))}return ret, nil}

Sys.go

Copy code from github.com/shirou/gopsutil//almost the same, but change a lot, especially the returned Structpackage Sy Simport ("Errors" "Io/ioutil" "StrConv" "strings") type SysStat struct {///proc/loadavgload1 float64load5 FLOAT64LOAD15      float64///proc/meminfototal uint64available uint64used uint64usedpercent float64free uint64Active  Uint64inactive uint64buffers uint64cached uint64wired uint64shared uint64///proc/net/dev//sum Of all Interfacesname stringbytessent uint64bytesrecv uint64packetssent uint64packetsrecv uint64///proc/statC PU stringuser float64system float64idle float64nice float64iowait FLOAT64IRQ float64softi RQ float64steal float64guest Float64guestnice float64stolen float64}func getsysstat () *SysStat {stat: = new (S Ysstat) Stat.cputimes () stat.netiocounters () stat.virtualmemory () Stat.loadavg () return Stat}func (stat *SysStat) Cputimes () error {filename: = "/proc/staT "var lines = []string{}lines, _ = readlinesoffsetn (filename, 0, 1) Err: = Stat.parsestatline (lines[0]) if err! = Nil {retur n Err}return nil}func (stat *sysstat) Parsestatline (line string), error {fields: = strings. Fields (line) if strings. Hasprefix (Fields[0], "cpu") = = false {return errors. New ("not contain CPU")}CPU: = fields[0]if CPU = = "CPU" {CPU = "Cpu-total"}user, err: = StrConv. Parsefloat (Fields[1], up) if err! = Nil {return Err}nice, err: = StrConv. Parsefloat (Fields[2], up) if err! = Nil {return Err}system, err: = StrConv. Parsefloat (Fields[3], up) if err! = Nil {return err}idle, err: = StrConv. Parsefloat (Fields[4], up) if err! = Nil {return err}iowait, err: = StrConv. Parsefloat (Fields[5], up) if err! = Nil {return ERR}IRQ, err: = StrConv. Parsefloat (Fields[6], up) if err! = Nil {return ERR}SOFTIRQ, err: = StrConv. Parsefloat (Fields[7], up) if err! = Nil {return Err}stolen, err: = StrConv. Parsefloat (Fields[8], max) if err! = Nil {return Err}cpu_tick: = float64 (+)//todo:how to get _SC_CLK_TCK Stat. CPU = Cpustat. user = float64 (user)/Cpu_tickstat. Nice = Float64 (Nice)/Cpu_tickstat. System = Float64 (System)/Cpu_tickstat. Idle = float64 (idle)/Cpu_tickstat. iowait = float64 (iowait)/Cpu_tickstat. IRQ = float64 (IRQ)/Cpu_tickstat. SOFTIRQ = float64 (SOFTIRQ)/Cpu_tickstat. Stolen = float64 (Stolen)/Cpu_tickif len (Fields) > 9 {//Linux >= 2.6.11steal, err: = StrConv. Parsefloat (Fields[9], up) if err! = Nil {return err}stat. Steal = Float64 (steal)}if len (fields) > {//Linux >= 2.6.24guest, err: = StrConv. Parsefloat (fields[10], up) if err! = Nil {return err}stat. Guest = Float64 (guest)}if len (fields) > {//Linux >= 3.2.0guestNice, err: = StrConv. Parsefloat (fields[11], up) if err! = Nil {return err}stat. Guestnice = float64 (guestnice)}return nil}type netiocountersstat struct {Name stringbytessent uint64bytesrecv u Int64packetssent uint64packetsrecv Uint64}func (stat *sysstat) netiocounters () error {filename: = "/proc/net/dev" lines, ERR: = ReadLines (filename) if err! = Nil {return Err}statlen: = Len (lines)-1all: = Make ([]netiocountersstat, 0, Statlen) for _, line: = R Ange lines[2:] {parts: = strings. SPLITN (Line, ":", 2) If Len (parts)! = 2 {continue}interfacename: = strings. Trimspace (Parts[0]) if InterfaceName = = "" {continue}fields: = strings. Fields (strings. Trimspace (Parts[1])) BYTESRECV, err: = StrConv. Parseuint (Fields[0], ten, max) if err! = Nil {return ERR}PACKETSRECV, err: = StrConv. Parseuint (Fields[1], ten, max) if err! = Nil {return err}bytessent, err: = StrConv. Parseuint (Fields[8], ten, max) if err! = Nil {return err}packetssent, err: = StrConv. Parseuint (Fields[9], ten, max) if err! = Nil {return Err}nic: = Netiocountersstat{name:interfacename,bytesrecv:byt Esrecv,packetsrecv:packetsrecv,bytessent:bytessent,packetssent:packetssent}all = append (all, Nic)}return Stat.getnetiocountersall (All)}func (stat *sysstat) getnetiocountersall (n []netiocountersstat) error {Stat. Name = "All-interfaces" for _, Nic: = Range N {Stat. BytesreCV + = nic. Bytesrecvstat.packetsrecv + = nic. Packetsrecvstat.bytessent + = nic. Bytessentstat.packetssent + = nic. Packetssent}return Nil}func (stat *sysstat) virtualmemory () error {filename: = "/proc/meminfo" lines, _: = ReadLines (filen AME) for _, Line: = Range lines {fields: = strings. Split (line, ': ') If Len (fields)! = 2 {continue}key: = strings. Trimspace (Fields[0]) Value: = Strings. Trimspace (fields[1]) value = strings. Replace (Value, "KB", "",-1) t, err: = StrConv. Parseuint (value, ten, max) if err! = Nil {return Err}switch key {case "Memtotal": Stat. Total = T * 1000case "Memfree": Stat. Free = T * 1000case "buffers": Stat. buffers = T * 1000case "Cached": Stat. Cached = T * 1000case "Active": Stat. Active = T * 1000case "Inactive": Stat. Inactive = T * 1000}}stat. Available = Stat. Free + Stat. Buffers + Stat. cachedstat.used = Stat. Total-stat. Freestat.usedpercent = float64 (Stat. total-stat.available)/float64 (Stat. Total) * 100.0return Nil}func (stat *sysstat) Loadavg () error {filename: = '/proc/loadavg ' line, ERR: = Ioutil. ReadFile (filename) if err! = Nil {return err}values: = Strings. Fields (String) load1, err: = StrConv. Parsefloat (Values[0], up) if err! = Nil {return ERR}LOAD5, err: = StrConv. Parsefloat (Values[1], up) if err! = Nil {return err}load15, err: = StrConv. Parsefloat (Values[2], up) if err! = Nil {return err}stat. Load1 = Load1stat. LOAD5 = Load5stat. LOAD15 = Load15return Nil}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.