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

dashboard: add two new endpoints to dashboard for Nomad examples #6

Merged
merged 1 commit into from
Apr 21, 2020
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
1 change: 1 addition & 0 deletions services/dashboard-service/.gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
rice-box.go
dist/*
dashboard-service
85 changes: 69 additions & 16 deletions services/dashboard-service/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@ package main

import (
"encoding/json"
"expvar"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"sync"
"time"

rice "github.com/GeertJohan/go.rice"
Expand All @@ -29,9 +32,13 @@ func main() {
fmt.Printf("Using counting service at %s\n", countingServiceURL)
fmt.Println("(Pass as COUNTING_SERVICE_URL environment variable)")

failTrack := new(failureTracker)

router := mux.NewRouter()
router.PathPrefix("/socket.io/").Handler(startWebsocket())
router.PathPrefix("/socket.io/").Handler(startWebsocket(failTrack))
router.HandleFunc("/health", HealthHandler)
router.HandleFunc("/health/api", HealthAPIHandler(failTrack))
router.Handle("/metrics", expvar.Handler())
router.PathPrefix("/").Handler(http.FileServer(rice.MustFindBox("assets").HTTPBox()))

log.Fatal(http.ListenAndServe(portWithColon, router))
Expand All @@ -44,37 +51,83 @@ func getEnvOrDefault(key, fallback string) string {
return fallback
}

// HealthHandler returns a succesful status and a message.
// HealthHandler returns a successful status and a message.
// For use by Consul or other processes that need to verify service health.
func HealthHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Hello, you've hit %s\n", r.URL.Path)
}

func startWebsocket() *gosocketio.Server {
type failureTracker struct {
lock sync.RWMutex
latest bool // indicates condition of most recent connection attempt
failures int // counts the number of consecutive connection failures
}

func (ft *failureTracker) Count(ok bool) {
ft.lock.Lock()
defer ft.lock.Unlock()

if ft.latest = ok; ok {
ft.failures = 0
} else {
ft.failures++
}
}

func (ft *failureTracker) Status() (bool, int) {
ft.lock.RLock()
defer ft.lock.RUnlock()
return ft.latest, ft.failures
}

// HealthAPIHandler returns the condition of the connectivity between the
// dashboard and the backend API server.
func HealthAPIHandler(ft *failureTracker) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
statusOK, failures := ft.Status()
if statusOK {
w.WriteHeader(http.StatusOK)
_, _ = io.WriteString(w, "ok")
} else {
w.WriteHeader(http.StatusServiceUnavailable)
_, _ = io.WriteString(w, fmt.Sprintf(
"failures: %d", failures,
))
}
}
}

func startWebsocket(ft *failureTracker) *gosocketio.Server {
server := gosocketio.NewServer(transport.GetDefaultWebsocketTransport())

fmt.Println("Starting websocket server...")
server.On(gosocketio.OnConnection, handleConnection)
server.On("send", handleSend)
server.On(gosocketio.OnConnection, handleConnectionFunc(ft))
server.On("send", handleSendFunc(ft))

return server
}

func handleConnection(c *gosocketio.Channel) {
fmt.Println("New client connected")
c.Join("visits")
handleSend(c, Count{})
func handleConnectionFunc(ft *failureTracker) func(c *gosocketio.Channel) {
return func(c *gosocketio.Channel) {
fmt.Println("New client connected")
c.Join("visits")
handleSendFunc(ft)(c, Count{})
}
}

func handleSend(c *gosocketio.Channel, msg Count) string {
count, err := getAndParseCount()
if err != nil {
count = Count{Count: -1, Message: err.Error(), Hostname: "[Unreachable]"}
func handleSendFunc(ft *failureTracker) func(*gosocketio.Channel, Count) string {
return func(c *gosocketio.Channel, msg Count) string {
count, err := getAndParseCount()
if err != nil {
count = Count{Count: -1, Message: err.Error(), Hostname: "[Unreachable]"}
ft.Count(false)
}
fmt.Println("Fetched count", count.Count)
c.Ack("message", count, time.Second*10)
ft.Count(true)
return "OK"
}
fmt.Println("Fetched count", count.Count)
c.Ack("message", count, time.Second*10)
return "OK"
}

// Count stores a number that is being counted and other data to send to
Expand Down