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

fix: perf #40

Merged
merged 1 commit into from
Apr 17, 2024
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
2 changes: 1 addition & 1 deletion src/api/qbittorrent.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ type Preferences struct {
UpLimit int `json:"up_limit"`
}

type Maindata struct {
type MainData struct {
CategoryMap map[string]Category `json:"categories"`
ServerState struct {
AlltimeDl int `json:"alltime_dl"`
Expand Down
31 changes: 31 additions & 0 deletions src/app/app.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package app

import "strings"

var (
Port int
ShouldShowError bool
DisableTracker bool
LogLevel string
BaseUrl string
Cookie string
Username string
Password string
)

func SetApp(port int, disableTracker bool, loglevel string) {
Port = port
ShouldShowError = false
DisableTracker = disableTracker
LogLevel = loglevel
}

func SetQbit(baseUrl string, username string, password string) {
BaseUrl = baseUrl
Username = username
Password = password
}

func GetPasswordMasked() string {
return strings.Repeat("*", len(Password))
}
2 changes: 1 addition & 1 deletion src/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ require (
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/prometheus/client_model v0.6.1 // indirect
github.com/prometheus/common v0.52.2 // indirect
github.com/prometheus/common v0.52.3 // indirect
github.com/prometheus/procfs v0.13.0 // indirect
golang.org/x/sys v0.19.0 // indirect
google.golang.org/protobuf v1.33.0 // indirect
Expand Down
4 changes: 2 additions & 2 deletions src/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ github.com/prometheus/client_golang v1.19.0 h1:ygXvpU1AoN1MhdzckN+PyD9QJOSD4x7km
github.com/prometheus/client_golang v1.19.0/go.mod h1:ZRM9uEAypZakd+q/x7+gmsvXdURP+DABIEIjnmDdp+k=
github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E=
github.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY=
github.com/prometheus/common v0.52.2 h1:LW8Vk7BccEdONfrJBDffQGRtpSzi5CQaRZGtboOO2ck=
github.com/prometheus/common v0.52.2/go.mod h1:lrWtQx+iDfn2mbH5GUzlH9TSHyfZpHkSiG1W7y3sF2Q=
github.com/prometheus/common v0.52.3 h1:5f8uj6ZwHSscOGNdIQg6OiZv/ybiK2CO2q2drVZAQSA=
github.com/prometheus/common v0.52.3/go.mod h1:BrxBKv3FWBIGXw89Mg1AeBq7FSyRzXWI3l3e7W3RN5U=
github.com/prometheus/procfs v0.13.0 h1:GqzLlQyfsPbaEHaQkO7tbDlriv/4o5Hudv6OXHGKX7o=
github.com/prometheus/procfs v0.13.0/go.mod h1:cd4PFCR54QLnGKPaKGA6l+cfuNXtht43ZKY6tow0Y1g=
golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o=
Expand Down
29 changes: 10 additions & 19 deletions src/logger/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,22 @@ import (
"os"
)

type Level int
type PrettyHandler struct {
slog.Handler
}

var LogLevels = map[string]Level{
"TRACE": Trace,
var LogLevels = map[string]int{
"DEBUG": Debug,
"INFO": Info,
"WARN": Warn,
"ERROR": Error,
}

const (
Trace Level = -8
Debug Level = -4
Info Level = 0
Warn Level = 4
Error Level = 8
Debug int = -4
Info int = 0
Warn int = 4
Error int = 8
)

const (
Expand All @@ -32,17 +32,8 @@ const (
Green = "\033[32m"
Yellow = "\033[33m"
Blue = "\033[34m"
White = "\033[97m"
)

type PrettyHandlerOptions struct {
SlogOpts slog.HandlerOptions
}

type PrettyHandler struct {
slog.Handler
}

func (h *PrettyHandler) Handle(ctx context.Context, r slog.Record) error {
level := r.Level.String()
timeStr := fmt.Sprintf("[%02d-%02d-%02d %02d:%02d:%02d]", r.Time.Year(), r.Time.Month(), r.Time.Day(), r.Time.Hour(), r.Time.Minute(), r.Time.Second())
Expand All @@ -67,10 +58,10 @@ func (h *PrettyHandler) Handle(ctx context.Context, r slog.Record) error {

func NewPrettyHandler(
out io.Writer,
opts PrettyHandlerOptions,
opts slog.HandlerOptions,
) *PrettyHandler {
h := &PrettyHandler{
Handler: slog.NewTextHandler(out, &opts.SlogOpts),
Handler: slog.NewTextHandler(out, &opts),
}

return h
Expand Down
45 changes: 26 additions & 19 deletions src/init.go → src/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,16 @@ import (
"flag"
"fmt"
"log/slog"
"net"
"net/http"
"os"
"qbit-exp/models"
qbit "qbit-exp/qbit"
"strconv"
"strings"

"qbit-exp/qbit"

app "qbit-exp/app"
logger "qbit-exp/logger"
"strconv"
"strings"

"github.com/joho/godotenv"
"github.com/prometheus/client_golang/prometheus"
Expand All @@ -30,18 +32,18 @@ func main() {
loadenv()
fmt.Printf("%s (version %s)\n", ProjectName, Version)
fmt.Println("Author:", Author)
fmt.Println("Using log level: " + models.GetLogLevel())
fmt.Println("Using log level: " + app.LogLevel)

qbit.Auth(true)

logger.Log.Info("qbittorrent URL: " + models.Getbaseurl())
logger.Log.Info("username: " + models.GetUsername())
logger.Log.Info("password: " + models.Getpasswordmasked())
logger.Log.Info("qbittorrent URL: " + app.BaseUrl)
logger.Log.Info("username: " + app.Username)
logger.Log.Info("password: " + app.GetPasswordMasked())
logger.Log.Info("Started")
http.HandleFunc("/metrics", metrics)
addr := ":" + strconv.Itoa(models.GetPort())
if models.GetPort() != DEFAULTPORT {
logger.Log.Info("Listening on port " + strconv.Itoa(models.GetPort()))
addr := ":" + strconv.Itoa(app.Port)
if app.Port != DEFAULTPORT {
logger.Log.Info("Listening on port " + strconv.Itoa(app.Port))
}
err := http.ListenAndServe(addr, nil)
if err != nil {
Expand All @@ -50,9 +52,15 @@ func main() {
}

func metrics(w http.ResponseWriter, req *http.Request) {
logger.Log.Debug("New request")
ip, _, err := net.SplitHostPort(req.RemoteAddr)
if err == nil {
logger.Log.Debug("New request from " + ip)
} else {
logger.Log.Debug("New request from")
}

registry := prometheus.NewRegistry()
qbit.Allrequests(registry)
qbit.AllRequests(registry)
h := promhttp.HandlerFor(registry, promhttp.HandlerOpts{})
h.ServeHTTP(w, req)
}
Expand Down Expand Up @@ -86,8 +94,8 @@ func loadenv() {
panic("EXPORTER_PORT must be > 0 and < 65353")
}

models.SetApp(num, false, strings.ToLower(disableTracker) == "true", loglevel)
models.SetQbit(qbitURL, qbitUsername, qbitPassword)
app.SetApp(num, strings.ToLower(disableTracker) == "true", loglevel)
app.SetQbit(qbitURL, qbitUsername, qbitPassword)
}

func setLogLevel(logLevel string) string {
Expand All @@ -98,11 +106,10 @@ func setLogLevel(logLevel string) string {
level = logger.LogLevels[upperLogLevel]
}

opts := logger.PrettyHandlerOptions{
SlogOpts: slog.HandlerOptions{
Level: slog.Level(level),
},
opts := slog.HandlerOptions{
Level: slog.Level(level),
}

handler := logger.NewPrettyHandler(os.Stdout, opts)
logger.Log = slog.New(handler)
return upperLogLevel
Expand Down
39 changes: 0 additions & 39 deletions src/models/app.go

This file was deleted.

44 changes: 0 additions & 44 deletions src/models/qbit.go

This file was deleted.

3 changes: 1 addition & 2 deletions src/prometheus/prometheus.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ func isValidURL(input string) bool {
}

func Torrent(result *API.Info, r *prometheus.Registry) {

qbittorrent_eta := prometheus.NewGaugeVec(prometheus.GaugeOpts{
Name: "qbittorrent_torrent_eta",
Help: "The current ETA for each torrent (in seconds)",
Expand Down Expand Up @@ -250,7 +249,7 @@ func Trackers(result []*API.Trackers, r *prometheus.Registry) {

}

func MainData(result *API.Maindata, r *prometheus.Registry) {
func MainData(result *API.MainData, r *prometheus.Registry) {
globalratio, err := strconv.ParseFloat((*result).ServerState.GlobalRatio, 64)

if err != nil {
Expand Down
6 changes: 3 additions & 3 deletions src/prometheus/prometheus_test.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
package prom

import (
"qbit-exp/models"
app "qbit-exp/app"
"testing"
)

func TestMain(t *testing.T) {
models.SetQbit("http://localhost:8080", "admin", "adminadmin")
result := models.Getpasswordmasked()
app.SetQbit("http://localhost:8080", "admin", "adminadmin")
result := app.GetPasswordMasked()

if !isValidMaskedPassword(result) {
t.Errorf("Invalid masked password. Expected only asterisks, got: %s", result)
Expand Down
18 changes: 9 additions & 9 deletions src/qbit/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,22 @@ import (
"io"
"net/http"
"net/url"
app "qbit-exp/app"
"qbit-exp/logger"
"qbit-exp/models"
"strconv"
"strings"
)

func Auth(init bool) {
params := url.Values{
"username": {models.GetUsername()},
"password": {models.Getpassword()},
"username": {app.Username},
"password": {app.Password},
}
resp, err := http.PostForm(models.Getbaseurl()+"/api/v2/auth/login", params)
resp, err := http.PostForm(app.BaseUrl+"/api/v2/auth/login", params)
if err != nil {
if !models.GetPromptError() {
models.SetPromptError(true)
logger.Log.Warn("Can't connect to qbittorrent with url : " + models.Getbaseurl())
if !app.ShouldShowError {
app.ShouldShowError = true
logger.Log.Warn("Can't connect to qbittorrent with url : " + app.BaseUrl)
}
return
}
Expand All @@ -41,12 +41,12 @@ func Auth(init bool) {
panic("Authentication Error, check your qBittorrent username / password")
}

if models.GetPromptError() {
if app.ShouldShowError {
logger.Log.Info("New cookie stored")
}

cookie := resp.Header.Get("Set-Cookie")
cookieValue := strings.Split(strings.Split(cookie, ";")[0], "=")[1]
models.Setcookie(cookieValue)
app.Cookie = cookieValue

}
Loading
Loading