Skip to content
This repository has been archived by the owner on Jul 31, 2022. It is now read-only.

Commit

Permalink
feat(2.2.0): new request type: stats, implement metrics
Browse files Browse the repository at this point in the history
  • Loading branch information
auguwu committed Mar 5, 2022
1 parent 9b42a0f commit 4ebb1b1
Show file tree
Hide file tree
Showing 11 changed files with 527 additions and 17 deletions.
4 changes: 2 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
VERSION = $(shell cat ./version.json | jq .version | tr -d '"')
GIT_COMMIT = $(shell git rev-parse --short HEAD)
BUILD_DATE = $(shell go run ./cmd/builddate.go)
BUILD_DATE = $(shell go run ./cmd/build-date.go)

HOME_OS ?= $(shell go env GOOS)
ifeq ($(HOME_OS),linux)
Expand All @@ -22,7 +22,7 @@ endif
# Usage: `make build`
build:
@echo Building project...
go build -ldflags "-s -w -X main.version=${VERSION} -X main.commitHash=${GIT_COMMIT} -X \"main.buildDate=${BUILD_DATE}\"" -o $(TARGET_FILE)
go build -ldflags "-s -w -X nino.sh/timeouts/pkg.Version=${VERSION} -X nino.sh/timeouts/pkg.CommitHash=${GIT_COMMIT} -X \"nino.sh/timeouts/pkg.BuildDate=${BUILD_DATE}\"" -o $(TARGET_FILE)
@echo Built project! Use "$(TARGET_FILE)" to execute the project.

# Usage: `make clean`
Expand Down
File renamed without changes.
10 changes: 9 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,19 @@ require (
github.com/go-redis/redis/v8 v8.11.4
github.com/gorilla/websocket v1.5.0
github.com/joho/godotenv v1.4.0
github.com/prometheus/client_golang v1.12.1
github.com/sirupsen/logrus v1.8.1
)

require (
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.1.2 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
golang.org/x/sys v0.0.0-20210423082822-04245dca01da // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
github.com/prometheus/client_model v0.2.0 // indirect
github.com/prometheus/common v0.32.1 // indirect
github.com/prometheus/procfs v0.7.3 // indirect
golang.org/x/sys v0.0.0-20220114195835-da31bd327af9 // indirect
google.golang.org/protobuf v1.26.0 // indirect
)
412 changes: 408 additions & 4 deletions go.sum

Large diffs are not rendered by default.

16 changes: 9 additions & 7 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
"encoding/json"
"fmt"
"github.com/joho/godotenv"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/sirupsen/logrus"
"net/http"
"nino.sh/timeouts/pkg"
Expand All @@ -34,12 +35,6 @@ import (
"time"
)

var (
version string
commitHash string
buildDate string
)

func init() {
// Setup logging
if os.Getenv("DEBUG") == "true" {
Expand All @@ -58,7 +53,7 @@ func init() {
}
}

logrus.Infof("Using v%s (commit: %s, built at: %s)", version, commitHash, buildDate)
logrus.Infof("Using v%s (commit: %s, built at: %s)", pkg.Version, pkg.CommitHash, pkg.BuildDate)
}

func fallbackEnv(envString string, fallback string) string {
Expand All @@ -77,7 +72,14 @@ func main() {
// Create a new `Server` instance
pkg.NewServer()

enableMetrics := pkg.SetupMetrics()

http.HandleFunc("/", pkg.HandleRequest)

if enableMetrics {
http.HandleFunc("/metrics", promhttp.Handler().ServeHTTP)
}

server := &http.Server{
Addr: fmt.Sprintf(":%s", fallbackEnv(os.Getenv("PORT"), "4025")),
Handler: nil,
Expand Down
14 changes: 14 additions & 0 deletions pkg/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import (
"fmt"
"github.com/gorilla/websocket"
"github.com/sirupsen/logrus"
"runtime"
"strings"
"sync"
"time"
Expand Down Expand Up @@ -156,5 +157,18 @@ func (c *Client) HandleMessage(msg Message) {
{
c.HandleTimeout(toTimeout(msg.Data.(map[string]interface{})))
}

case Stats:
{
c.WriteMessage(Message{
OP: Stats,
Data: map[string]interface{}{
"go_version": strings.TrimPrefix(runtime.GOOS, "go"),
"version": Version,
"commit_sha": CommitHash,
"build_date": BuildDate,
},
})
}
}
}
7 changes: 7 additions & 0 deletions pkg/constants.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package pkg

var (
Version = "master"
CommitHash = "???"
BuildDate = "???"
)
58 changes: 58 additions & 0 deletions pkg/metrics.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
// Copyright (c) 2021 Nino
//
// 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 pkg

import (
"github.com/prometheus/client_golang/prometheus"
"github.com/sirupsen/logrus"
"os"
)

var (
TimeoutMetric = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "nino_timeouts_timeouts",
Help: "How many timeouts the service is handling",
})

TimeoutLatencyMetric = prometheus.NewHistogram(prometheus.HistogramOpts{
Name: "nino_timeouts_average_ws_latency",
Help: "The latency to process a WebSocket message.",
})
)

func SetupMetrics() bool {
enabled, ok := os.LookupEnv("NINO_TIMEOUTS_METRICS_ENABLED")

if !ok {
logrus.Infof("`NINO_TIMEOUTS_METRICS_ENABLED` was not defined, disabling metrics...")
return false
}

if enabled == "false" || enabled == "0" {
logrus.Infof("Not enabling metrics due to `NINO_TIMEOUTS_METRICS_ENABLED` being disabled.")
return false
}

logrus.Infof("Now setting up collector registry...")
prometheus.MustRegister(TimeoutMetric, TimeoutLatencyMetric)

return true
}
20 changes: 18 additions & 2 deletions pkg/socket.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ package pkg
import (
"context"
"encoding/json"
"github.com/go-redis/redis/v8"
"github.com/gorilla/websocket"
"github.com/sirupsen/logrus"
"net/http"
Expand Down Expand Up @@ -67,8 +68,23 @@ func NewServer() {
// Overwrite queue based off Redis
data, err := Redis.Connection.Get(context.TODO(), "nino:timeouts").Result()
if err != nil {
logrus.Warnf("Unable to retrieve all timeouts, are we connected?\n%v", err)
return
if err == redis.Nil {
logrus.Warnf("We have retrieved `null` when fetching for timeouts, skipping as empty queue.")

// Set it to an empty array
err = Redis.Connection.HMSet(context.TODO(), "nino:timeouts", []Timeout{}).Err()
if err != nil {
logrus.Errorf("Unable to set data as an empty array. :<")
return
}

logrus.Infof("Queue has been set in Redis, now starting fresh!")
Server.Queue = make([]Timeout, 0)
return
} else {
logrus.Warnf("Unable to retrieve all timeouts, are we connected?\n%v", err)
return
}
}

// serialize output to []Timeout{}
Expand Down
1 change: 1 addition & 0 deletions pkg/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ const (
Apply
Request
RequestAll
Stats
)

type Message struct {
Expand Down
2 changes: 1 addition & 1 deletion version.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{
"version": "2.1.0"
"version": "2.2.0"
}

0 comments on commit 4ebb1b1

Please sign in to comment.