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

CPU Information #20

Merged
merged 5 commits into from
May 1, 2023
Merged
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
8 changes: 7 additions & 1 deletion cmd/excubitor/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package cmd
import (
ctx "github.com/Excubitor-Monitoring/Excubitor-Backend/internal/context"
"github.com/Excubitor-Monitoring/Excubitor-Backend/internal/http_server"
"github.com/Excubitor-Monitoring/Excubitor-Backend/internal/integrated_modules/cpuinfo"
"github.com/Excubitor-Monitoring/Excubitor-Backend/internal/logging"
"github.com/Excubitor-Monitoring/Excubitor-Backend/internal/pubsub"
)
Expand All @@ -17,7 +18,12 @@ func Execute() error {
}

context := ctx.GetContext()
context.RegisterModule(ctx.NewModule("main"))

context.RegisterModule(ctx.NewModule("main", func() {
logger.Trace("Tick!")
}))
context.RegisterModule(ctx.NewModule("cpu", cpuinfo.Tick))

context.RegisterBroker(pubsub.NewBroker())

logger.Debug("Starting HTTP Server!")
Expand Down
15 changes: 15 additions & 0 deletions internal/context/clock.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package ctx

import "time"

func startClock() {
go func() {
for {
modules := GetContext().GetModules()
for _, module := range modules {
module.tickFunction()
}
time.Sleep(1000 * time.Millisecond)
}
}()
}
13 changes: 10 additions & 3 deletions internal/context/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@ import (
)

type Module struct {
Name string `json:"name"`
Name string `json:"name"`
tickFunction func()
}

func NewModule(name string) *Module {
return &Module{name}
func NewModule(name string, tickFunction func()) *Module {
return &Module{name, tickFunction}
}

type Context struct {
Expand Down Expand Up @@ -41,7 +42,13 @@ func (ctx *Context) RegisterModule(module *Module) {
ctx.lock.RLock()
defer ctx.lock.RUnlock()

var once sync.Once

ctx.modules[module.Name] = module

once.Do(func() {
startClock()
})
}

func (ctx *Context) GetModules() []Module {
Expand Down
2 changes: 1 addition & 1 deletion internal/http_server/http_server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
)

func TestInfo(t *testing.T) {
ctx.GetContext().RegisterModule(ctx.NewModule("TestModule"))
ctx.GetContext().RegisterModule(ctx.NewModule("TestModule", func() {}))

req := httptest.NewRequest(http.MethodGet, "/info", nil)
w := httptest.NewRecorder()
Expand Down
22 changes: 15 additions & 7 deletions internal/http_server/websocket.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"github.com/gobwas/ws"
"github.com/gobwas/ws/wsutil"
"net"
"sync"
)

type OpCode string
Expand Down Expand Up @@ -114,16 +115,23 @@ func handleWebsocket(conn net.Conn) {
switch content.OpCode {
case GET:
temporarySubscriber := broker.AddSubscriber()

var receiveOnce sync.Once

logger.Trace(fmt.Sprintf("Added temporary subscriber to fulfill GET request from %s on monitor %s.", clientAddress, content.Target))

go temporarySubscriber.Listen(func(m *pubsub.Message) {
logger.Trace(fmt.Sprintf("Sending single message from %s to connection from %s", m.GetMonitor(), clientAddress))
temporarySubscriber.Destruct()
err = sendMessage(conn, newMessage(REPLY, TargetAddress(m.GetMonitor()), m.GetMessageBody()))
if err != nil {
logger.Error(fmt.Sprintf("Couldn't send message to %s. Aborting connection...", clientAddress))
return
}
receiveOnce.Do(func() {
logger.Trace(fmt.Sprintf("Sending single message from %s to connection from %s", m.GetMonitor(), clientAddress))
broker.Unsubscribe(temporarySubscriber, string(content.Target))
defer temporarySubscriber.Destruct()

err = sendMessage(conn, newMessage(REPLY, TargetAddress(m.GetMonitor()), m.GetMessageBody()))
if err != nil {
logger.Error(fmt.Sprintf("Couldn't send message to %s. Aborting connection...", clientAddress))
return
}
})
})

broker.Subscribe(temporarySubscriber, string(content.Target))
Expand Down
94 changes: 94 additions & 0 deletions internal/integrated_modules/cpuinfo/cpu.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package cpuinfo

import (
"fmt"
"regexp"
"strconv"
)

type cpu struct {
Id uint `json:"id"`
CoreId uint `json:"core_id"`
SocketId uint `json:"socket_id"`
ModelName string `json:"model_name"`
ClockSpeed float64 `json:"clock_speed"`
CacheSize uint `json:"cache_size"`
Flags string `json:"flags"`
}

// readCPU parses a single thread/core from a cpuinfo file into a cpu struct.
func readCPU(paragraph string) (*cpu, error) {
id, err := getUInt("processor", paragraph)
if err != nil {
return nil, fmt.Errorf("could not parse processor id: %w", err)
}

coreId, err := getUInt("core id", paragraph)
if err != nil {
return nil, fmt.Errorf("could not parse core id: %w", err)
}

socketId, err := getUInt("physical id", paragraph)
if err != nil {
return nil, fmt.Errorf("could not parse physical id: %w", err)
}

modelName, err := getString("model name", paragraph)
if err != nil {
return nil, fmt.Errorf("could not parse model name: %w", err)
}

clockSpeed, err := getFloat64("cpu MHz", paragraph)
if err != nil {
return nil, fmt.Errorf("could not parse clock speed: %w", err)
}

cache, err := getUInt("cache size", paragraph)
if err != nil {
return nil, fmt.Errorf("could not parse cache size: %w", err)
}

flags, err := getString("flags", paragraph)
if err != nil {
return nil, fmt.Errorf("could not parse flags: %w", err)
}

return &cpu{
Id: id,
CoreId: coreId,
SocketId: socketId,
ModelName: modelName,
ClockSpeed: clockSpeed,
CacheSize: cache,
Flags: flags,
}, nil
}

func getUInt(name string, paragraph string) (uint, error) {
regex := regexp.MustCompile(name + `\s+:\s+(\d+)`)
matches := regex.FindStringSubmatch(paragraph)
value, err := strconv.ParseUint(matches[1], 10, 32)
if err != nil {
return 9999, err
}

return uint(value), nil
}

func getFloat64(name string, paragraph string) (float64, error) {
regex := regexp.MustCompile(name + `\s+:\s+([[:digit:]]+.[[:digit:]]+)`)
matches := regex.FindStringSubmatch(paragraph)
value, err := strconv.ParseFloat(matches[1], 64)
if err != nil {
return 9999, err
}

return value, nil
}

func getString(name string, paragraph string) (string, error) {
regex := regexp.MustCompile(name + `\s+:\s+([[:print:]]+)`)
matches := regex.FindStringSubmatch(paragraph)

return matches[1], nil
}
49 changes: 49 additions & 0 deletions internal/integrated_modules/cpuinfo/cpu_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package cpuinfo

import (
"github.com/stretchr/testify/assert"
"testing"
)

func TestReadCPU(t *testing.T) {
testData := `processor : 2
vendor_id : GenuineIntel
cpu family : 6
model : 158
model name : Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz
stepping : 9
microcode : 0xf0
cpu MHz : 4500.034
cache size : 8192 KB
physical id : 0
siblings : 8
core id : 2
cpu cores : 4
apicid : 4
initial apicid : 4
fpu : yes
fpu_exception : yes
cpuid level : 22
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb invpcid_single pti ssbd ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid mpx rdseed adx smap clflushopt intel_pt xsaveopt xsavec xgetbv1 xsaves dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp md_clear flush_l1d arch_capabilities
vmx flags : vnmi preemption_timer invvpid ept_x_only ept_ad ept_1gb flexpriority tsc_offset vtpr mtf vapic ept vpid unrestricted_guest ple shadow_vmcs pml ept_mode_based_exec
bugs : cpu_meltdown spectre_v1 spectre_v2 spec_store_bypass l1tf mds swapgs taa itlb_multihit srbds mmio_stale_data retbleed
bogomips : 8400.00
clflush size : 64
cache_alignment : 64
address sizes : 39 bits physical, 48 bits virtual
power management:`

cpu, err := readCPU(testData)
if err != nil {
return
}

assert.Equal(t, uint(2), cpu.Id)
assert.Equal(t, uint(2), cpu.CoreId)
assert.Equal(t, uint(0), cpu.SocketId)
assert.Equal(t, "Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz", cpu.ModelName)
assert.Equal(t, 4500.034, cpu.ClockSpeed)
assert.Equal(t, uint(8192), cpu.CacheSize)
assert.Equal(t, "fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb invpcid_single pti ssbd ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid mpx rdseed adx smap clflushopt intel_pt xsaveopt xsavec xgetbv1 xsaves dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp md_clear flush_l1d arch_capabilities", cpu.Flags)
}
63 changes: 63 additions & 0 deletions internal/integrated_modules/cpuinfo/cpuinfo.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package cpuinfo

import (
"encoding/json"
"fmt"
ctx "github.com/Excubitor-Monitoring/Excubitor-Backend/internal/context"
"github.com/Excubitor-Monitoring/Excubitor-Backend/internal/logging"
"os"
"regexp"
)

var logger logging.Logger

// Tick is a function that is called whenever the context wants the module to report its values.
func Tick() {
logger = logging.GetLogger()

cpuInfo, err := readCPUInfoFile()
if err != nil {
logger.Error(fmt.Sprintf("Could not read /proc/cpuinfo! Reason: %s", err))
return
}

cpus, err := readCPUInfo(string(cpuInfo))
if err != nil {
logger.Error(fmt.Sprintf("Could not gather cpu information! Reason: %s", err))
return
}

jsonOutput, err := json.Marshal(cpus)
if err != nil {
logger.Error(fmt.Sprintf("Couldn't encode cpu information! Reason: %s", err))
return
}

broker := ctx.GetContext().GetBroker()
broker.Publish("CPU.CpuInfo", string(jsonOutput))
}

// readCPUInfoFile reads the contents of /proc/cpuinfo and returns them in a byte slice.
func readCPUInfoFile() ([]byte, error) {
file, err := os.ReadFile("/proc/cpuinfo")
return file, err
}

// readCPUInfo can parse multiple threads from a cpuinfo file.
func readCPUInfo(cpuInfo string) ([]cpu, error) {
paragraphs := regexp.MustCompile(`\n\s*\n`).Split(cpuInfo, -1)

cpus := make([]cpu, len(paragraphs)-1)

for i, p := range paragraphs {
if len(p) != 0 {
cpu, err := readCPU(p)
if err != nil {
return nil, err
}
cpus[i] = *cpu
}
}

return cpus, nil
}
Loading