Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added CPU usage block #19

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ The main goal of this project is to have all of the status indicator modules wri
* RAID status (mdraid only)
* filesystem usage
* system load
* CPU usage
* memory availability
* CPU temperature
* network interfaces (up/down status, IP addresses)
Expand Down
8 changes: 8 additions & 0 deletions config/goblocks-full.yml
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,14 @@ blocks:
label: "L: "
crit_load: 4

# The CPU usage in percents.
- type: cpu
label: "U: "
crit_usage: 0.8
# By default an aggregated value for all cores is displayed.
# Individual core on multi-core machine can be specified. See /proc/stat for possible values.
# cpu: cpu0

# The memory block displays available memory.
- type: memory
label: "M: "
Expand Down
5 changes: 5 additions & 0 deletions lib/modules/configure.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,11 @@ func getBlockConfigInstance(m map[string]interface{}) (*BlockConfig, error) {
err := yaml.Unmarshal(yamlStr, &c)
b := BlockConfig(c)
return &b, err
case "cpu":
c := &Cpu{}
err := yaml.Unmarshal(yamlStr, &c)
b := (BlockConfig)(c)
return &b, err
case "disk":
c := Disk{}
err := yaml.Unmarshal(yamlStr, &c)
Expand Down
83 changes: 83 additions & 0 deletions lib/modules/cpu.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package modules

import (
"bufio"
"errors"
"fmt"
"github.com/davidscholberg/go-i3barjson"
"os"
"strconv"
"strings"
)

// Cpu represents the configuration for the cpu block.
type Cpu struct {
BlockConfigBase `yaml:",inline"`
Cpu string `yaml:"cpu"` // name of the cpu to display (from /proc/stat), empty = all
CritUsage float64 `yaml:"crit_usage"`

lastIdle uint64
lastTotal uint64
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm a little bit uneasy with putting the lastIdle and lastTotal variables in this struct. Strictly speaking, this struct is for configuration data, not dynamic data that needs to persist over update calls. However, I do realize that there's currently no good way to persist dynamic data from one update call to the next.

I'm kind of leaning towards making these global variables rather than fields of the Cpu struct. I know that's not ideal, but it will at least keep dynamic data out of the configuration struct until we have a better solution for persisting data.

Any thoughts on this?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I understand.

I think it would be great if the whole goblocks design was based around blocks that are once configured from YAML and live until the program exits. The block would then encapsulate its configuration, state and provide an interface to render itself on screen. I actually though this is the way how it worked when I coded the CPU block. I think it is more documentation/mental and probably pointer receiver problem than anything else.

I was also thinking about moving the state of the block to a global variable and the best design I can come with is this:

type cpuState struct {
	lastIdle  uint64
	lastTotal uint64
}

// name of the CPU -> block state
var cpuStates map[string]cpuState

It has the shorcoming that it does not support creating a block for the same cpu twice. It is rather theoretical problem but it points to a more higher level problem.

BTW is guaranteed that the UpdateBlock functions are called from one goroutine? Otherwise the state access would have to be synchronized.

}

// UpdateBlock updates the status of the CPU block.
// The block displays the CPU usage since the last update.
func (c *Cpu) UpdateBlock(b *i3barjson.Block) {
b.Color = c.Color

usage, err := c.getCpuUsage()
if err != nil {
b.FullText = err.Error()
b.Urgent = true
return
}

b.Urgent = (c.CritUsage > 0) && (usage > c.CritUsage)
b.FullText = fmt.Sprintf("%s%2.0f%%", c.Label, 100*usage)
}

// getCpuUsage returns the usage of the configured CPU. It does by reading /proc/stat and
// calculating (1 - idle_time/total_time).
func (c *Cpu) getCpuUsage() (float64, error) {
f, err := os.Open("/proc/stat")
if err != nil {
return 0, err
}
defer f.Close()

// find the line that corresponds to the configured CPU
s := bufio.NewScanner(f)
for s.Scan() {
flds := strings.Fields(s.Text())
if c.Cpu == "" || (len(flds) > 0 && flds[0] == c.Cpu) {
return c.parseCpuLine(flds[1:])
}
}
if s.Err() != nil {
return 0, s.Err()
}
return 0, fmt.Errorf("cpu %s not found", c.Cpu)
}

// parseCpuLine extracts the usage from the text fields of one line of /proc/stat.
func (c *Cpu) parseCpuLine(flds []string) (float64, error) {
// CPU lines have 10 fields since kernel version 2.6.33
if len(flds) < 10 {
return 0, errors.New("invalid line in /proc/stat")
}
var total, idle uint64
for i := range flds {
val, err := strconv.ParseUint(flds[i], 10, 64)
if err != nil {
return 0, errors.New("invalid number")
}
total += val
if i == 3 {
idle += val
}

}
usage := 1 - (float64(idle-c.lastIdle) / float64(total-c.lastTotal))
c.lastTotal, c.lastIdle = total, idle
return usage, nil
}