Skip to content

Commit

Permalink
Merge pull request #37 from bluewave-labs/ci/lint
Browse files Browse the repository at this point in the history
Remove unimplemented codes & Lint Fixes
  • Loading branch information
ajhollid authored Dec 19, 2024
2 parents aace293 + ba2ab5f commit e984e73
Show file tree
Hide file tree
Showing 13 changed files with 61 additions and 134 deletions.
19 changes: 19 additions & 0 deletions .github/workflows/lint.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
name: lint

on:
pull_request:
branches:
- main
- develop

jobs:
lint:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0

- name: Golangci-lint
uses: golangci/[email protected]
17 changes: 7 additions & 10 deletions cmd/capture/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ var appConfig = config.NewConfig(
func main() {
r := gin.Default()
apiV1 := r.Group("/api/v1")
apiV1.Use(middleware.AuthRequired(appConfig.ApiSecret))
apiV1.Use(middleware.AuthRequired(appConfig.APISecret))

// Health Check
apiV1.GET("/health", handler.Health)
Expand All @@ -35,12 +35,10 @@ func main() {
apiV1.GET("/metrics/disk", handler.MetricsDisk)
apiV1.GET("/metrics/host", handler.MetricsHost)

// WebSocket Connection
apiV1.GET("/ws/metrics", handler.WebSocket)

server := &http.Server{
Addr: ":" + appConfig.Port,
Handler: r.Handler(),
Addr: ":" + appConfig.Port,
Handler: r.Handler(),
ReadHeaderTimeout: 5 * time.Second,
}

// Graceful shutdown
Expand All @@ -57,10 +55,9 @@ func main() {
if err := server.Shutdown(ctx); err != nil {
log.Fatal("server shutdown:", err)
}
select {
case <-ctx.Done():
log.Println("timeout of 5 seconds.")
}
<-ctx.Done()
log.Println("timeout of 5 seconds.")

log.Println("server exiting")
}

Expand Down
1 change: 0 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ go 1.23.1

require (
github.com/gin-gonic/gin v1.10.0
github.com/gorilla/websocket v1.5.3
github.com/shirou/gopsutil/v4 v4.24.9
github.com/stretchr/testify v1.9.0
)
Expand Down
2 changes: 0 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,6 @@ github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
Expand Down
6 changes: 3 additions & 3 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import "log"

type Config struct {
Port string
ApiSecret string
APISecret string
}

var defaultPort = "59232"
Expand All @@ -22,13 +22,13 @@ func NewConfig(port string, apiSecret string) *Config {

return &Config{
Port: port,
ApiSecret: apiSecret,
APISecret: apiSecret,
}
}

func Default() *Config {
return &Config{
Port: defaultPort,
ApiSecret: "",
APISecret: "",
}
}
5 changes: 2 additions & 3 deletions internal/handler/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,10 @@ func handleMetricResponse(c *gin.Context, metrics metric.Metric, errs []metric.C
if len(errs) > 0 {
statusCode = 207
}
c.JSON(statusCode, metric.ApiResponse{
c.JSON(statusCode, metric.APIResponse{
Data: metrics,
Errors: errs,
})
return
}

func Metrics(c *gin.Context) {
Expand All @@ -23,7 +22,7 @@ func Metrics(c *gin.Context) {
}

func MetricsCPU(c *gin.Context) {
cpuMetrics, metricsErrs := metric.CollectCpuMetrics()
cpuMetrics, metricsErrs := metric.CollectCPUMetrics()
handleMetricResponse(c, cpuMetrics, metricsErrs)
}

Expand Down
79 changes: 0 additions & 79 deletions internal/handler/websocket.go

This file was deleted.

8 changes: 4 additions & 4 deletions internal/metric/cpu.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
"github.com/shirou/gopsutil/v4/cpu"
)

func CollectCpuMetrics() (*CpuData, []CustomErr) {
func CollectCPUMetrics() (*CPUData, []CustomErr) {
// Collect CPU Core Counts
cpuPhysicalCoreCount, cpuPhysicalErr := cpu.Counts(false)
cpuLogicalCoreCount, cpuLogicalErr := cpu.Counts(true)
Expand Down Expand Up @@ -60,7 +60,7 @@ func CollectCpuMetrics() (*CpuData, []CustomErr) {
}

// Collect CPU Temperature from sysfs
cpuTemp, cpuTempErr := sysfs.CpuTemperature()
cpuTemp, cpuTempErr := sysfs.CPUTemperature()

if cpuTempErr != nil {
cpuErrors = append(cpuErrors, CustomErr{
Expand All @@ -70,7 +70,7 @@ func CollectCpuMetrics() (*CpuData, []CustomErr) {
cpuTemp = nil
}

cpuCurrentFrequency, cpuCurFreqErr := sysfs.CpuCurrentFrequency()
cpuCurrentFrequency, cpuCurFreqErr := sysfs.CPUCurrentFrequency()
if cpuCurFreqErr != nil {
cpuErrors = append(cpuErrors, CustomErr{
Metric: []string{"cpu.current_frequency"},
Expand All @@ -79,7 +79,7 @@ func CollectCpuMetrics() (*CpuData, []CustomErr) {
cpuCurrentFrequency = 0
}

return &CpuData{
return &CPUData{
PhysicalCore: cpuPhysicalCoreCount,
LogicalCore: cpuLogicalCoreCount,
Frequency: cpuFrequency,
Expand Down
22 changes: 9 additions & 13 deletions internal/metric/disk.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,15 @@ import (
func CollectDiskMetrics() (MetricsSlice, []CustomErr) {
defaultDiskData := []*DiskData{
{
Device: "unknown",
ReadSpeedBytes: nil,
WriteSpeedBytes: nil,
TotalBytes: nil,
FreeBytes: nil,
UsagePercent: nil,
Device: "unknown",
TotalBytes: nil,
FreeBytes: nil,
UsagePercent: nil,
},
}
var diskErrors []CustomErr
var metricsSlice MetricsSlice
var checkedSlice []string // To keep track of checked partitions
var checkedSlice = make([]string, 0, 10) // To keep track of checked partitions

// Set all flag to "false" to get only necessary partitions
// Avoiding unnecessary partitions like /run/user/1000, /run/credentials
Expand Down Expand Up @@ -52,12 +50,10 @@ func CollectDiskMetrics() (MetricsSlice, []CustomErr) {

checkedSlice = append(checkedSlice, p.Device)
metricsSlice = append(metricsSlice, &DiskData{
Device: p.Device,
ReadSpeedBytes: nil, // TODO: Implement
WriteSpeedBytes: nil, // TODO: Implement
TotalBytes: &diskUsage.Total,
FreeBytes: &diskUsage.Free,
UsagePercent: RoundFloatPtr(diskUsage.UsedPercent/100, 4),
Device: p.Device,
TotalBytes: &diskUsage.Total,
FreeBytes: &diskUsage.Free,
UsagePercent: RoundFloatPtr(diskUsage.UsedPercent/100, 4),
})
}

Expand Down
22 changes: 10 additions & 12 deletions internal/metric/metric.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@ type Metric interface {
isMetric()
}

type ApiResponse struct {
type APIResponse struct {
Data Metric `json:"data"`
Errors []CustomErr `json:"errors"`
}

type AllMetrics struct {
Cpu CpuData `json:"cpu"`
CPU CPUData `json:"cpu"`
Memory MemoryData `json:"memory"`
Disk MetricsSlice `json:"disk"`
Host HostData `json:"host"`
Expand All @@ -27,7 +27,7 @@ type CustomErr struct {
Error string `json:"err"`
}

type CpuData struct {
type CPUData struct {
PhysicalCore int `json:"physical_core"` // Physical cores
LogicalCore int `json:"logical_core"` // Logical cores aka Threads
Frequency float64 `json:"frequency"` // Frequency in mHz
Expand All @@ -37,7 +37,7 @@ type CpuData struct {
UsagePercent float64 `json:"usage_percent"` // Usage percentage //* Total - Idle / Total
}

func (c CpuData) isMetric() {}
func (c CPUData) isMetric() {}

type MemoryData struct {
TotalBytes uint64 `json:"total_bytes"` // Total space in bytes
Expand All @@ -49,12 +49,10 @@ type MemoryData struct {
func (m MemoryData) isMetric() {}

type DiskData struct {
Device string `json:"device"` // Device
ReadSpeedBytes *uint64 `json:"read_speed_bytes"` // TODO: Implement
WriteSpeedBytes *uint64 `json:"write_speed_bytes"` // TODO: Implement
TotalBytes *uint64 `json:"total_bytes"` // Total space of device in bytes
FreeBytes *uint64 `json:"free_bytes"` // Free space of device in bytes
UsagePercent *float64 `json:"usage_percent"` // Usage Percent of device
Device string `json:"device"` // Device
TotalBytes *uint64 `json:"total_bytes"` // Total space of device in bytes
FreeBytes *uint64 `json:"free_bytes"` // Free space of device in bytes
UsagePercent *float64 `json:"usage_percent"` // Usage Percent of device
}

func (d DiskData) isMetric() {}
Expand All @@ -68,7 +66,7 @@ type HostData struct {
func (h HostData) isMetric() {}

func GetAllSystemMetrics() (AllMetrics, []CustomErr) {
cpu, cpuErr := CollectCpuMetrics()
cpu, cpuErr := CollectCPUMetrics()
memory, memErr := CollectMemoryMetrics()
disk, diskErr := CollectDiskMetrics()
host, hostErr := GetHostInformation()
Expand All @@ -92,7 +90,7 @@ func GetAllSystemMetrics() (AllMetrics, []CustomErr) {
}

return AllMetrics{
Cpu: *cpu,
CPU: *cpu,
Memory: *memory,
Disk: disk,
Host: *host,
Expand Down
4 changes: 2 additions & 2 deletions internal/metric/metric_math.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ func RoundFloat(val float64, precision uint) float64 {
return prc
}

func RandomIntPtr(max int64) *int {
n, err := rand.Int(rand.Reader, big.NewInt(max))
func RandomIntPtr(maximum int64) *int {
n, err := rand.Int(rand.Reader, big.NewInt(maximum))
if err != nil {
panic(err) // handle error appropriately in production
}
Expand Down
8 changes: 4 additions & 4 deletions internal/sysfs/cpu.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ func readTempFile(path string) (float32, error) {
return float32(temp) / 1000, nil
}

func readCpuFreqFile(path string) (int, error) {
func readCPUFreqFile(path string) (int, error) {
data, err := os.ReadFile(path)
if err != nil {
return 0, err
Expand All @@ -36,7 +36,7 @@ func readCpuFreqFile(path string) (int, error) {
return freq, nil
}

func CpuTemperature() ([]float32, error) {
func CPUTemperature() ([]float32, error) {
// Look in all these folders for core temp
corePaths := []string{
"/sys/devices/platform/coretemp.0/hwmon/hwmon*/temp*_input",
Expand Down Expand Up @@ -74,8 +74,8 @@ func CpuTemperature() ([]float32, error) {
return temps, nil
}

func CpuCurrentFrequency() (int, error) {
frequency, cpuFrequencyError := readCpuFreqFile("/sys/devices/system/cpu/cpufreq/policy0/scaling_cur_freq")
func CPUCurrentFrequency() (int, error) {
frequency, cpuFrequencyError := readCPUFreqFile("/sys/devices/system/cpu/cpufreq/policy0/scaling_cur_freq")

if cpuFrequencyError != nil {
return 0, cpuFrequencyError
Expand Down
2 changes: 1 addition & 1 deletion internal/sysfs/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (

func ShellExec(c string) (string, error) {
if strings.Contains(c, "&&") || strings.Contains(c, "||") || strings.Contains(c, ";") {
return "", errors.New("It's forbidden to execute consecutive commands")
return "", errors.New("it's forbidden to execute consecutive commands")
}
cmd := exec.Command("bash", "-c", c)

Expand Down

0 comments on commit e984e73

Please sign in to comment.