go_watcher

package module
v0.0.0-...-ec9f5bd Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 5, 2022 License: MIT Imports: 9 Imported by: 0

README

GO_Watcher

Lets you monitor the CPU- and Memory Usage of your System. Additonally added the number of Goroutines. Offers a webservice, for remote access, with updates regularly via websockets.. Compiled binary is <10mb in size and has a small memory/cpu footprint.

Uses

  • Websockets
  • Flags
  • Goolge Charts
  • Github Actions

Added Dockerfile for the funsies

Build image with:
docker build --tag go_watcher .

Run container with:
docker run --rm -p 8080:8080 go_watcher

Input

  • -addr :8080 -> Changes to Port and Address of the Server
  • -period 1s -> Changes the Update Speed of the Graph/Websocket

Todo

  • Tests!
  • More Infos
  • Change Chart to Running
  • Add better Timestamp
  • ...

Documentation

Index

Constants

This section is empty.

Variables

View Source
var HomeTemplate = template.Must(template.New("").Parse(`
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="icon" href="data:,">
</head>
<body>
<div id="chart_div"></div>
<div id="chart_mem"></div>
<div id="chart_go"></div>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script>
		var data;
		var chart;
		var ws_data;
		var index = 0;

		var mem_data;
		var mem_chart;
		var mem_ws_data;
		var mem_index = 0;

		var go_data;
		var go_chart;
		var go_ws_data;
		var go_index = 0;

		// create options object with titles, colors, etc.
		let options = {
			title: "CPU Usage",
			hAxis: {
				title: "Time"
			},
			vAxis: {
				title: "Usage"
			}
		};

		// create options object with titles, colors, etc.
		let mem_options = {
			title: "Memory Usage",
			hAxis: {
				title: "Time"
			},
			vAxis: {
				title: "Usage"
			}
		};
		
		// create options object with titles, colors, etc.
		let go_options = {
			title: "Num Goroutines",
			hAxis: {
				title: "Time"
			},
			vAxis: {
				title: "Usage"
			}
		};

		// Das hier weils wichtig ist ob https oder nicht.
		// Browser erlauben KEIN downgrad also https zu ws!
		if (location.protocol === 'https:'){
			ws = new WebSocket("wss://" + document.location.host  + document.location.pathname + "echo");
		} else {
			ws = new WebSocket("ws://" + document.location.host  + document.location.pathname + "echo");
		}


		ws.onopen = function(evt) {
			console.log("OPEN");
		}

		ws.onclose = function(evt) {
			document.getElementById("Load").innerText = "Closed by Server"
			console.log("CLOSE");
		}

		// Listen for messages
		ws.addEventListener('message', function (event) {
			
			console.log('Message from server ', JSON.parse(event.data));
			ws_data = JSON.parse(event.data)

			data.addRow([index, ws_data.cpu_load]);
			chart.draw(data, options);
			index++;

			mem_data.addRow([mem_index, ws_data.mem_load]);
			mem_chart.draw(mem_data, mem_options);
			mem_index++;

			go_data.addRow([go_index, ws_data.goroutines]);
			go_chart.draw(go_data, go_options);
			go_index++;

		});

		ws.onerror = function(evt) {
			document.getElementById("Load").innerText = "Erro occured"
			console.log("ERROR: " + evt);
		}

        // load current chart package
        google.charts.load("current", {
            packages: ["corechart", "line"]
        });
        // set callback function when api loaded
        google.charts.setOnLoadCallback(drawChart);
        function drawChart() {
            // create data object with default value
            data = google.visualization.arrayToDataTable([
                ["Year", "CPU Usage"],
                [0, 0]
            ]);
			// create data object with default value
            mem_data = google.visualization.arrayToDataTable([
                ["Year", "Mem Usage"],
                [0, 100]
            ]);
			// create data object with default value
            go_data = google.visualization.arrayToDataTable([
                ["Year", "Goroutines"],
                [0, 25]
            ]);

			
			chart = new google.visualization.LineChart(
                document.getElementById("chart_div")
            );
            chart.draw(data, options);

			mem_chart = new google.visualization.LineChart(
                document.getElementById("chart_mem")
            );
            mem_chart.draw(mem_data, options);

			go_chart = new google.visualization.LineChart(
                document.getElementById("chart_go")
            );
            go_chart.draw(mem_data, options);
        }
    </script>
</body>
</html>
`))
View Source
var PollPeriod time.Duration

Functions

func GetCPULoad

func GetCPULoad(Stats *PC_stats, interval time.Duration)

GetCPULoad changes PC_StatsCPU_Load each interval.

func GetGoroutines

func GetGoroutines(Stats *PC_stats, interval time.Duration)

GetCPULoad changes PC_StatsCPU_Load each interval.

func GetMemLoad

func GetMemLoad(Stats *PC_stats, interval time.Duration)

GetMemLoad changes PC_Stats.Mem_Load each interval.

This goroutine also writes the Timestamp to PC_Stats.

func MessageReceiver

func MessageReceiver(ctx context.Context, conn *websocket.Conn, close chan bool)

MessageReceiver is needed to listen on the Closes from the Client side.

If you don´t listen to those messages, the Programm will try to write, on a dead connection and fail.

func MessageWriter

func MessageWriter(ctx context.Context, conn *websocket.Conn, poll *time.Ticker, pong *time.Ticker)

MessageWriter writes to the Connection, at specified interval.

If the connection is closed on the client side, the goroutine is notified via the C_close Channel and returns. Additionally it regularly writes a PingMessage to the connection.

func SendTemplate

func SendTemplate(w http.ResponseWriter, r *http.Request)

SendTemplate sends a HMTL which creates a Websocket Connection an updates Graphs. To function the SendUpdate function needs to added as *"echo"* and located relativ to this Path. For example:

http.HandleFunc("/echo", SendUpdates)
http.HandleFunc("/", SendTemplate)

func SendUpdates

func SendUpdates(w http.ResponseWriter, r *http.Request)

SendStatusUpdates implements to Websocket Logik. So far I could not come up with an Idea how to stop MessageReceiver. Dont know how if thats bad...

func Start

func Start(pollPeriod time.Duration) error

Start starts 3 Goroutines that update the Global Variable "Stats", each pollPeriod

Types

type PC_stats

type PC_stats struct {
	CPU_Load   float64   `json:"cpu_load"`
	Mem_Load   float64   `json:"mem_load"`
	Goroutines int       `json:"goroutines"`
	Timestamp  time.Time `json:"timestamp"`
}
var Stats PC_stats

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL