本文整理汇总了Golang中github.com/shirou/gopsutil/load.LoadAvg函数的典型用法代码示例。如果您正苦于以下问题:Golang LoadAvg函数的具体用法?Golang LoadAvg怎么用?Golang LoadAvg使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了LoadAvg函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Gather
func (_ *SystemStats) Gather(acc telegraf.Accumulator) error {
loadavg, err := load.LoadAvg()
if err != nil {
return err
}
hostinfo, err := host.HostInfo()
if err != nil {
return err
}
users, err := host.Users()
if err != nil {
return err
}
fields := map[string]interface{}{
"load1": loadavg.Load1,
"load5": loadavg.Load5,
"load15": loadavg.Load15,
"uptime": hostinfo.Uptime,
"n_users": len(users),
"uptime_format": format_uptime(hostinfo.Uptime),
"n_cpus": runtime.NumCPU(),
}
acc.AddFields("system", fields, nil)
return nil
}
示例2: loadAvg
func loadAvg(ns []string) (*plugin.PluginMetricType, error) {
load, err := load.LoadAvg()
if err != nil {
return nil, err
}
switch joinNamespace(ns) {
case "/intel/psutil/load/load1":
return &plugin.PluginMetricType{
Namespace_: ns,
Data_: load.Load1,
}, nil
case "/intel/psutil/load/load5":
return &plugin.PluginMetricType{
Namespace_: ns,
Data_: load.Load5,
}, nil
case "/intel/psutil/load/load15":
return &plugin.PluginMetricType{
Namespace_: ns,
Data_: load.Load15,
}, nil
}
return nil, fmt.Errorf("Unknown error processing %v", ns)
}
示例3: loadAvg
func loadAvg() string {
l, err := load.LoadAvg()
if err != nil {
log.Println(err)
}
return fmt.Sprintf("%5s %5s %5s", humanize.Ftoa(l.Load1), humanize.Ftoa(l.Load5), humanize.Ftoa(l.Load15))
}
示例4: startNode
func startNode(masterHost, name string) {
var sock mangos.Socket
var err error
var msg []byte
masterUrl := url.URL{Scheme: "tcp", Host: masterHost}
ip := getPrivateIP()
// Try to get new "respondent" socket
if sock, err = respondent.NewSocket(); err != nil {
utils.Die("Can't get new respondent socket: %s", err.Error())
}
defer sock.Close()
sock.AddTransport(tcp.NewTransport())
// Connect to master
if err = sock.Dial(masterUrl.String()); err != nil {
utils.Die("Can't dial on respondent socket: %s", err.Error())
}
// Wait for a survey request and send responses
for {
if msg, err = sock.Recv(); err != nil {
utils.Die("Cannot recv: %s", err.Error())
}
fmt.Printf("Client(%s): Received \"%s\" survey request\n", name, string(msg))
var loadAvg *load.LoadAvgStat
if loadAvg, err = load.LoadAvg(); err != nil {
utils.Die("Cannot get load average: %s", err.Error())
}
var cpuInfo []cpu.CPUInfoStat
if cpuInfo, err = cpu.CPUInfo(); err != nil {
utils.Die("Cannot get CPU info: %s", err.Error())
}
fmt.Printf("CPU INFO len: %d\n", len(cpuInfo))
// Get the normalized CPU load
avg := loadAvg.Load1
cores := int32(0)
for _, info := range cpuInfo {
fmt.Printf("Inner Cores: %d\n", info.Cores)
cores += info.Cores
}
fmt.Printf("Load avg: %f\n", avg)
fmt.Printf("Cores: %d\n", cores)
avg = avg / float64(cores)
fmt.Printf("Client(%s): Sending survey response\n", name)
if err = sock.Send([]byte(fmt.Sprintf("%s,%f", ip, avg))); err != nil {
utils.Die("Cannot send: %s", err.Error())
}
}
}
示例5: Load_f
func Load_f() (*LoadAvgStat_j, error) {
load, _ := load.LoadAvg()
timestamp := time.Now().Unix()
// fmt.Println(mem)
ret := &LoadAvgStat_j{
Load1: load.Load1,
Load5: load.Load5,
Load15: load.Load15,
Timestamp: timestamp,
}
return ret, nil
}
示例6: LoadAverage
// LoadAverage - returns load avg
func LoadAverage() LoadStruct {
cores, _ := cpu.CPUCounts(true)
load, _ := load.LoadAvg()
l := LoadStruct{
Minute: load.Load1,
FiveMinutes: load.Load5,
FifteenMinutes: load.Load15,
Cores: cores,
}
return l
}
示例7: Gather
func (_ *SystemStats) Gather(acc plugins.Accumulator) error {
loadavg, err := load.LoadAvg()
if err != nil {
return err
}
hostinfo, err := host.HostInfo()
if err != nil {
return err
}
acc.Add("load1", loadavg.Load1, nil)
acc.Add("load5", loadavg.Load5, nil)
acc.Add("load15", loadavg.Load15, nil)
acc.Add("uptime", hostinfo.Uptime, nil)
acc.Add("uptime_format", format_uptime(hostinfo.Uptime), nil)
return nil
}
示例8: Gather
func (_ *SystemStats) Gather(acc inputs.Accumulator) error {
loadavg, err := load.LoadAvg()
if err != nil {
return err
}
hostinfo, err := host.HostInfo()
if err != nil {
return err
}
fields := map[string]interface{}{
"load1": loadavg.Load1,
"load5": loadavg.Load5,
"load15": loadavg.Load15,
"uptime": hostinfo.Uptime,
"uptime_format": format_uptime(hostinfo.Uptime),
}
acc.AddFields("system", fields, nil)
return nil
}
示例9: getStats
func getStats() *hash {
var m, l *hash
if stat, err := mem.VirtualMemory(); err == nil {
m = &hash{
"total": bytesToKB(stat.Total),
"free": bytesToKB(stat.Free),
"buffers": bytesToKB(stat.Buffers),
"cached": bytesToKB(stat.Cached),
"free_total": bytesToKB(stat.Free + stat.Buffers + stat.Cached),
}
}
if stat, err := load.LoadAvg(); err == nil {
l = &hash{
"one": stat.Load1,
"five": stat.Load5,
"fifteen": stat.Load15,
}
}
return &hash{"mem": m, "load": l}
}
示例10: main
func main() {
header, _ := json.Marshal(Header{Version: 1})
fmt.Println(string(header))
fmt.Println("[")
go notifyd()
for {
if mode == "standard" {
line := make([]Block, 0)
// TIME block
t := time.Now()
const t_format = "2006-01-02 15:04:05"
time_block := Block{
Name: "time",
FullText: t.Format(t_format),
Color: GRAY,
}
// LOAD block
load, _ := load.LoadAvg()
load_block := Block{
Name: "load",
FullText: strconv.FormatFloat(load.Load1, 'f', 2, 64),
}
if load.Load1 > 2 {
load_block.Color = BAD
} else if load.Load1 > 1 {
load_block.Color = WARN
} else {
load_block.Color = OKAY
}
// NET block
net_blocks := make([]Block, 0)
interfaces, _ := net.NetInterfaces()
for _, iface := range interfaces {
if iface.Name == "lo" {
continue
}
text := iface.Addrs[0].Addr
net_blocks = append(net_blocks, Block{
Name: "iface",
FullText: text,
Instance: iface.Name,
Color: GRAY,
})
}
// HDD block
root_stat, _ := disk.DiskUsage("/")
home_stat, _ := disk.DiskUsage("/home")
data_stat, _ := disk.DiskUsage("/media/me/data")
root_block := Block{
Name: "hdd",
Instance: "root",
FullText: FormatGigabytes(root_stat.Free) + "GB",
}
if root_stat.Free > 5*1024*1024*1024 {
root_block.Color = OKAY
} else if root_stat.Free > 2.5*1024*1024*1024 {
root_block.Color = WARN
} else {
root_block.Color = BAD
}
home_block := Block{
Name: "hdd",
Instance: "root",
FullText: FormatGigabytes(home_stat.Free) + "GB",
}
if home_stat.Free > 20*1024*1024*1024 {
home_block.Color = OKAY
} else if home_stat.Free > 10*1024*1024*1024 {
home_block.Color = WARN
} else {
home_block.Color = BAD
}
data_block := Block{
Name: "hdd",
Instance: "data",
FullText: FormatGigabytes(data_stat.Free) + "GB",
}
if data_stat.Free > 30*1024*1024*1024 {
data_block.Color = OKAY
} else if data_stat.Free > 15*1024*1024*1024 {
data_block.Color = WARN
} else {
data_block.Color = BAD
}
/* // Headphones block
headphones := Block {
Name: "headphones",
FullText: "Headphones ",
}
if exec.Command("sh", "-c", "pacmd list-sinks | grep DR-BTN200").Run() == nil {
headphones.FullText += "connected";
headphones.Color = OKAY;
//.........这里部分代码省略.........
示例11: stat
func (st *Stat) stat(t string) string {
checkErr := func(err error) string {
return "系统酱正在食用作死药丸中..."
}
switch t {
case "free":
m, err := mem.VirtualMemory()
checkErr(err)
s, err := mem.SwapMemory()
checkErr(err)
mem := new(runtime.MemStats)
runtime.ReadMemStats(mem)
return fmt.Sprintf(
"全局:\n"+
"Total: %s Free: %s\nUsed: %s %s%%\nCache: %s\n"+
"Swap:\nTotal: %s Free: %s\n Used: %s %s%%\n"+
"群组娘:\n"+
"Allocated: %s\nTotal Allocated: %s\nSystem: %s\n",
helper.HumanByte(m.Total, m.Free, m.Used, m.UsedPercent, m.Cached,
s.Total, s.Free, s.Used, s.UsedPercent,
mem.Alloc, mem.TotalAlloc, mem.Sys)...,
)
case "df":
fs, err := disk.DiskPartitions(false)
checkErr(err)
var buf bytes.Buffer
for k := range fs {
du, err := disk.DiskUsage(fs[k].Mountpoint)
switch {
case err != nil, du.UsedPercent == 0, du.Free == 0:
continue
}
f := fmt.Sprintf("Mountpoint: %s Type: %s \n"+
"Total: %s Free: %s \nUsed: %s %s%%\n",
helper.HumanByte(fs[k].Mountpoint, fs[k].Fstype,
du.Total, du.Free, du.Used, du.UsedPercent)...,
)
buf.WriteString(f)
}
return buf.String()
case "os":
h, err := host.HostInfo()
checkErr(err)
uptime := time.Duration(time.Now().Unix()-int64(h.Uptime)) * time.Second
l, err := load.LoadAvg()
checkErr(err)
c, err := cpu.CPUPercent(time.Second*3, false)
checkErr(err)
return fmt.Sprintf(
"OSRelease: %s\nHostName: %s\nUptime: %s\nLoadAvg: %.2f %.2f %.2f\n"+
"Goroutine: %d\nCPU: %.2f%%",
h.Platform, h.Hostname, uptime.String(), l.Load1, l.Load5, l.Load15,
runtime.NumGoroutine(), c[0],
)
case "redis":
info := conf.Redis.Info().Val()
if info != "" {
infos := strings.Split(info, "\r\n")
infoMap := make(map[string]string)
for k := range infos {
line := strings.Split(infos[k], ":")
if len(line) > 1 {
infoMap[line[0]] = line[1]
}
}
DBSize := conf.Redis.DbSize().Val()
return fmt.Sprintf("Redis Version: %s\nOS: %s\nUsed Memory: %s\n"+
"Used Memory Peak: %s\nDB Size: %d\n",
infoMap["redis_version"], infoMap["os"], infoMap["used_memory_human"],
infoMap["used_memory_peak_human"], DBSize)
}
return ""
default:
return "欢迎来到未知领域(ゝ∀・)"
}
}
示例12: main
func main() {
httpPort := os.Getenv("PORT")
if len(httpPort) == 0 {
httpPort = "8080"
}
r := gin.Default()
// Limit all requests to 10 per second
//limitHandler := tollbooth_gin.LimitHandler(tollbooth.NewLimiter(600, 60*time.Second))
limitHandler := func(c *gin.Context) {
c.Next()
}
persistEvents()
r.Use(staticHandler)
r.Use(corsHandler)
r.Use(func(c *gin.Context) {
start := time.Now()
c.Next()
end := time.Now()
latency := end.Sub(start)
mutex.Lock()
if _, ok := db["incr:request"]; !ok {
db["incr:request"] = incr.NewEvent()
}
db["incr:request"].Add(incr.Time(time.Now().Unix()), incr.Value(latency), "")
mutex.Unlock()
})
go func() {
for _ = range time.Tick(time.Second) {
mutex.Lock()
if _, ok := db["incr:goalloc"]; !ok {
db["incr:goalloc"] = incr.NewEvent()
db["incr:memused"] = incr.NewEvent()
db["incr:load:1"] = incr.NewEvent()
db["incr:load:5"] = incr.NewEvent()
db["incr:load:15"] = incr.NewEvent()
}
now := incr.Time(time.Now().Unix())
var memstats runtime.MemStats
runtime.ReadMemStats(&memstats)
db["incr:goalloc"].Add(now, incr.Value(memstats.Alloc), "")
if vmem, err := mem.VirtualMemory(); err == nil {
db["incr:memused"].Add(now, incr.Value(vmem.Used), "")
}
if load, err := load.LoadAvg(); err == nil {
db["incr:load:1"].Add(now, incr.Value(load.Load1), "")
db["incr:load:5"].Add(now, incr.Value(load.Load5), "")
db["incr:load:15"].Add(now, incr.Value(load.Load15), "")
}
mutex.Unlock()
}
}()
r.Any("/:name/:value", limitHandler, func(c *gin.Context) {
name := c.Params.ByName("name")
value, _ := strconv.ParseFloat(c.Params.ByName("value"), 64)
sender := ""
if c, err := c.Request.Cookie("sender"); err == nil {
sender = c.Value
}
mutex.Lock()
defer mutex.Unlock()
if _, ok := db[name]; !ok {
// TODO: Limit requests to 10 per day
db[name] = incr.NewEvent()
}
if date := c.Request.Header.Get("Date"); date != "" {
if d, err := time.Parse(http.TimeFormat, date); err == nil {
if diff := d.Sub(time.Now()); math.Abs(diff.Hours()) < 24 {
db[name].Add(incr.Time(d.Unix()), incr.Value(value), sender)
return
}
}
}
db[name].Add(incr.Time(time.Now().Unix()), incr.Value(value), sender)
if c.Request.Method == "GET" {
c.Data(200, "image/gif", minimalGIF)
}
})
r.GET("/:name", limitHandler, func(c *gin.Context) {
mutex.RLock()
defer mutex.RUnlock()
e, ok := db[c.Params.ByName("name")]
if !ok {
e = incr.NewEvent()
}
//.........这里部分代码省略.........
示例13: Value
func (o *LoadMetric) Value() (float64, error) {
l, e := load.LoadAvg()
return l.Load1, e
}
示例14: main
func main() {
c := config{
URL: "http://localhost:8086",
Database: "test",
Interval: 5 * time.Minute,
}
opts.New(&c).Name("sysflux").Version(VERSION).Parse()
//validate config
u, err := url.Parse(c.URL)
if err != nil {
log.Fatal("Invalid URL")
}
host, port, err := net.SplitHostPort(u.Host)
if err != nil {
log.Fatal("Invalid host and port")
}
if u.Path == "" {
u.Path = "/write"
}
v := url.Values{}
v.Set("db", c.Database)
u.RawQuery = v.Encode()
tags := ""
if c.Tags != "" {
tags = "," + c.Tags
}
//good to go
log.Printf("Using InfluxDB endpoint: %s", u)
success := false
lock := sync.Mutex{}
entries := []string{}
send := func() error {
body := strings.NewReader(strings.Join(entries, "\n"))
if c.DNS != "" {
//lookup host every POST
ips, err := lookup(host, c.DNS)
if err != nil {
return fmt.Errorf("Lookup failed: %s", err)
}
u.Host = ips[0] + ":" + port
}
resp, err := http.Post(u.String(), "application/x-www-form-urlencoded", body)
if err != nil {
return fmt.Errorf("HTTP POST failed: %s", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusNoContent {
msg, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("Response download failed: %s", err)
}
return fmt.Errorf("Response: %d => %s", resp.StatusCode, msg)
}
//show first success
if !success {
log.Printf("Success")
success = true
}
//clear once recieved!
entries = nil
return nil
}
report := func() {
t := time.Now().UnixNano()
if l, err := load.LoadAvg(); err == nil {
entries = append(entries, fmt.Sprintf("cpu_load_short%s value=%f %d", tags, l.Load1*100, t))
entries = append(entries, fmt.Sprintf("cpu_load_medium%s value=%f %d", tags, l.Load5*100, t))
entries = append(entries, fmt.Sprintf("cpu_load_long%s value=%f %d", tags, l.Load15*100, t))
}
if v, err := mem.VirtualMemory(); err == nil {
entries = append(entries, fmt.Sprintf("mem_usage%s value=%f %d", tags, v.UsedPercent, t))
}
if len(entries) > MAX_QUEUED {
entries = entries[len(entries)-MAX_QUEUED:]
}
}
//send loop
go func() {
b := backoff.Backoff{}
for {
wait := time.Second
lock.Lock()
if len(entries) > 0 {
if err := send(); err == nil {
b.Reset()
} else {
log.Println(err)
wait = b.Duration()
}
}
lock.Unlock()
time.Sleep(wait)
//.........这里部分代码省略.........
示例15:
)
var root = hateoas.NewResource(
hateoas.Path("/"),
hateoas.AddLink("cpus", cpuRsc),
hateoas.AddLink("load", loadRsc),
hateoas.AddLink("processes", procRsc),
hateoas.HEAD(mohttp.EmptyBodyHandler),
)
var cpuRsc = hateoas.NewResource(
hateoas.Path("/cpus"),
hateoas.GET(mohttp.DataHandlerFunc(func(c context.Context) (interface{}, error) {
return cpu.CPUInfo()
})),
)
var loadRsc = hateoas.NewResource(
hateoas.Path("/load"),
hateoas.GET(mohttp.DataHandlerFunc(func(c context.Context) (interface{}, error) {
return load.LoadAvg()
})),
)
var procRsc = hateoas.NewResource(
hateoas.Path("/processes"),
hateoas.GET(mohttp.DataHandlerFunc(func(c context.Context) (interface{}, error) {
return process.Pids()
})),
)