Skip to content

Commit

Permalink
Websocket server
Browse files Browse the repository at this point in the history
  • Loading branch information
Kashkovsky committed Apr 14, 2022
1 parent 92fed51 commit 78c2129
Show file tree
Hide file tree
Showing 8 changed files with 137 additions and 14 deletions.
2 changes: 2 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,12 @@ package cmd
import (
"os"

"github.com/Kashkovsky/hostmonitor/core"
"github.com/spf13/cobra"
)

var cfgFile string
var watchConfig = core.WatchConfig{}

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Expand Down
91 changes: 91 additions & 0 deletions cmd/serve.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/*
Copyright © 2022 Denys Kashkovskyi <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package cmd

import (
"log"
"net/http"
"sync"

"github.com/Kashkovsky/hostmonitor/core"
"github.com/gorilla/websocket"
"github.com/spf13/cobra"
)

// serveCmd represents the serve command
var serveCmd = &cobra.Command{
Use: "serve",
Short: "Spin up a websocket server",
Run: runServe,
}

func init() {
rootCmd.AddCommand(serveCmd)
serveCmd.Flags().StringVarP(&address, "address", "a", "0.0.0.0:8080", "Server address")
serveCmd.Flags().StringVarP(&watchConfig.ConfigUrl, "configUrl", "c", core.ITArmyConfigURL, "Url of config containing url list")
serveCmd.Flags().IntVarP(&watchConfig.TestInterval, "testInterval", "i", 20, "Interval in seconds between test updates")
serveCmd.Flags().IntVarP(&watchConfig.RequestTimeout, "requestTimeout", "t", 10, "Request timeout")
serveCmd.Flags().IntVarP(&watchConfig.UpdateInterval, "updateInterval", "u", 600, "Config update interval in seconds")

}

var upgrader = websocket.Upgrader{}
var address string

func runServe(cmd *cobra.Command, args []string) {
http.HandleFunc("/ws", serveWs)
http.HandleFunc("/", serveHome)
log.Fatal(http.ListenAndServe(address, nil))
}

func serveWs(w http.ResponseWriter, r *http.Request) {
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Print("upgrade:", err)
return
}

defer c.Close()
watcher := core.NewWatcher(&watchConfig)
mu := sync.Mutex{}

watcher.Watch(func(res core.TestResult) {
mu.Lock()
defer mu.Unlock()
err = c.WriteJSON(res)
if err != nil {
log.Println("write:", err)
}
})
}

func serveHome(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.Error(w, "Not found", http.StatusNotFound)
return
}
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
http.ServeFile(w, r, "home.html")
}
2 changes: 0 additions & 2 deletions cmd/watch.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,6 @@ import (
"github.com/spf13/cobra"
)

var watchConfig = core.WatchConfig{}

// watchCmd represents the watch command
var watchCmd = &cobra.Command{
Use: "watch",
Expand Down
6 changes: 3 additions & 3 deletions core/printer.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,9 @@ func (p *Printer) ToTable(results *sync.Map) {
if ok {
p.t.AppendRow(table.Row{
k,
testResult.tcp,
testResult.httpStatus,
testResult.duration,
testResult.Tcp,
testResult.HttpStatus,
testResult.Duration,
})
}
return true
Expand Down
18 changes: 9 additions & 9 deletions core/tester.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@ import (
)

type TestResult struct {
Id string
InProgress bool
Id string `json:"id"`
InProgress bool `json:"inProgress"`
url url.URL
tcp string
httpStatus string
duration string
Tcp string `json:"tcp"`
HttpStatus string `json:"httpStatus"`
Duration string `json:"duration"`
}

type Tester struct {
Expand Down Expand Up @@ -43,16 +43,16 @@ func (t *Tester) Test(url *url.URL) {
t.out <- TestResult{
Id: url.Host,
InProgress: true,
httpStatus: "Testing...",
HttpStatus: "Testing...",
}
pass := t.tcp(url)
status, duration := t.http(url)
t.out <- TestResult{
Id: url.Host,
url: *url,
tcp: fmt.Sprintf("%d/10", pass),
httpStatus: status,
duration: strconv.FormatInt(duration.Milliseconds(), 10) + "ms",
Tcp: fmt.Sprintf("%d/10", pass),
HttpStatus: status,
Duration: strconv.FormatInt(duration.Milliseconds(), 10) + "ms",
}
time.Sleep(t.testInterval)
}
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ require (
)

require (
github.com/gorilla/websocket v1.5.0
github.com/inconshreveable/mousetrap v1.0.0 // indirect
github.com/mattn/go-runewidth v0.0.13 // indirect
github.com/rivo/uniseg v0.2.0 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46t
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
github.com/jedib0t/go-pretty/v6 v6.3.0 h1:QQ5yZPDUMEjbZRXDJtZlvwfDQqCYFaxV3yEzTkogUgk=
Expand Down
29 changes: 29 additions & 0 deletions home.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script>
window.addEventListener("load", function (evt) {
const output = document.getElementById("output");
const print = function (message) {
const d = document.createElement("div");
d.textContent = message;
output.appendChild(d);
output.scroll(0, output.scrollHeight);
};
const url = `ws://${location.host}/ws`;
ws = new WebSocket(url);

ws.onmessage = function (evt) {
print(evt.data);
};
ws.onerror = function (evt) {
print("ERROR: " + evt.data);
};
});
</script>
</head>
<body>
<div id="output" style="max-height: 70vh; overflow-y: scroll"></div>
</body>
</html>

0 comments on commit 78c2129

Please sign in to comment.