Skip to content

Commit

Permalink
Add prometheus metrics and explicitly allow TZ to be passed for logging
Browse files Browse the repository at this point in the history
  • Loading branch information
j0sh3rs committed Aug 29, 2024
1 parent b9e6adb commit 5bb6a92
Show file tree
Hide file tree
Showing 3 changed files with 111 additions and 5 deletions.
2 changes: 1 addition & 1 deletion goreleaser.Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
FROM alpine:edge
RUN apk add --no-cache ca-certificates
RUN apk add --no-cache ca-certificates tzdata
COPY foxtrot /foxtrot
ENTRYPOINT ["/foxtrot"]
78 changes: 74 additions & 4 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
// Package main is meant to help bump the numbers of the Firefox User-Agent against US Gov Websites
// Package foxtrot is meant to help bump the numbers of the Firefox User-Agent against US Gov Websites
package main

import (
"context"
"encoding/csv"
"expvar"
"fmt"
"io"
"log"
"math/rand"
"net"
"net/http"
"os"
"strings"
"sync"
"time"
Expand All @@ -19,15 +21,40 @@ import (
)

var (
concurrency int
delay int
userAgent string
concurrency int
delay int
userAgent string
totalRequests int64
successfulRequests map[string]int64
failedRequests map[string]int64
mu sync.Mutex
location *time.Location
)

func init() {

successfulRequests = make(map[string]int64)
failedRequests = make(map[string]int64)
setTimeZone()
}

func setTimeZone() {
tz := os.Getenv("TZ")
if tz == "" {
tz = "UTC" // Default to UTC if no timezone is set
}
loc, err := time.LoadLocation(tz)
if err != nil {
log.Fatalf("Failed to load timezone %s: %v", tz, err)
}
location = loc
}

func sendRequest(client *http.Client, website string) {
req, err := http.NewRequest("GET", website, nil)
if err != nil {
log.Printf("Error creating request for %s: %v", website, err)
incrementFailedRequests(website)
return
}

Expand All @@ -36,13 +63,52 @@ func sendRequest(client *http.Client, website string) {
resp, err := client.Do(req)
if err != nil {
log.Printf("Error sending request to %s: %v", website, err)
incrementFailedRequests(website)
return
}
defer resp.Body.Close()

incrementTotalRequests()
if resp.StatusCode == http.StatusOK {
incrementSuccessfulRequests(website)
} else {
incrementFailedRequests(website)
}

log.Printf("Request to %s completed with status code: %d", website, resp.StatusCode)
}

func incrementTotalRequests() {
mu.Lock()
totalRequests++
mu.Unlock()
}

func incrementSuccessfulRequests(website string) {
mu.Lock()
successfulRequests[website]++
mu.Unlock()
}

func incrementFailedRequests(website string) {
mu.Lock()
failedRequests[website]++
mu.Unlock()
}

func metricsHandler(w http.ResponseWriter, r *http.Request) {
mu.Lock()
defer mu.Unlock()

fmt.Fprintf(w, "total_requests %d\n", totalRequests)
for site, count := range successfulRequests {
fmt.Fprintf(w, "successful_requests{website=\"%s\"} %d\n", site, count)
}
for site, count := range failedRequests {
fmt.Fprintf(w, "failed_requests{website=\"%s\"} %d\n", site, count)
}
}

func downloadWebsites(url string) ([]string, error) {
resp, err := http.Get(url)
if err != nil {
Expand Down Expand Up @@ -173,6 +239,10 @@ func main() {
Use: "foxtrot",
Short: "A simple golang script that will help bump Firefox's overall numbers on US Gov websites",
Run: func(cmd *cobra.Command, args []string) {
go func() {
http.Handle("/metrics", expvar.Handler())
log.Fatal(http.ListenAndServe(":9120", nil))
}()
run(downloadWebsites, sendRequest)
},
}
Expand Down
36 changes: 36 additions & 0 deletions main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,39 @@ func TestRun(t *testing.T) {

time.Sleep(2 * time.Second)
}

func TestMetrics(t *testing.T) {
mockDownloadWebsites := func(url string) ([]string, error) {
return []string{"https://example.com", "https://example.org"}, nil
}

mockSendRequest := func(client *http.Client, website string) {
incrementTotalRequests()
if website == "https://example.com" {
incrementSuccessfulRequests(website)
} else {
incrementFailedRequests(website)
}
}

go func() {
run(mockDownloadWebsites, mockSendRequest)
}()

time.Sleep(2 * time.Second)

mu.Lock()
defer mu.Unlock()

if totalRequests != 2 {
t.Errorf("Expected 2 total requests, got %d", totalRequests)
}

if successfulRequests["https://example.com"] != 1 {
t.Errorf("Expected 1 successful request for https://example.com, got %d", successfulRequests["https://example.com"])
}

if failedRequests["https://example.org"] != 1 {
t.Errorf("Expected 1 failed request for https://example.org, got %d", failedRequests["https://example.org"])
}
}

0 comments on commit 5bb6a92

Please sign in to comment.