Skip to content

Commit

Permalink
Add Prometheus metrics for number of plays. Add buffer for mpg123
Browse files Browse the repository at this point in the history
  • Loading branch information
marvinmartian committed Nov 7, 2023
1 parent 494f445 commit 1be581e
Show file tree
Hide file tree
Showing 3 changed files with 98 additions and 17 deletions.
13 changes: 13 additions & 0 deletions player/go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,16 @@
module go_rfid

go 1.21.3

require (
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/golang/protobuf v1.5.3 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect
github.com/prometheus/client_golang v1.17.0 // indirect
github.com/prometheus/client_model v0.4.1-0.20230718164431-9a2bf3000d16 // indirect
github.com/prometheus/common v0.44.0 // indirect
github.com/prometheus/procfs v0.11.1 // indirect
golang.org/x/sys v0.11.0 // indirect
google.golang.org/protobuf v1.31.0 // indirect
)
27 changes: 27 additions & 0 deletions player/go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg=
github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/matttproud/golang_protobuf_extensions v1.0.4 h1:mmDVorXM7PCGKw94cs5zkfA9PSy5pEvNWRP0ET0TIVo=
github.com/matttproud/golang_protobuf_extensions v1.0.4/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4=
github.com/prometheus/client_golang v1.17.0 h1:rl2sfwZMtSthVU752MqfjQozy7blglC+1SOtjMAMh+Q=
github.com/prometheus/client_golang v1.17.0/go.mod h1:VeL+gMmOAxkS2IqfCq0ZmHSL+LjWfWDUmp1mBz9JgUY=
github.com/prometheus/client_model v0.4.1-0.20230718164431-9a2bf3000d16 h1:v7DLqVdK4VrYkVD5diGdl4sxJurKJEMnODWRJlxV9oM=
github.com/prometheus/client_model v0.4.1-0.20230718164431-9a2bf3000d16/go.mod h1:oMQmHW1/JoDwqLtg57MGgP/Fb1CJEYF2imWWhWtMkYU=
github.com/prometheus/common v0.44.0 h1:+5BrQJwiBB9xsMygAB3TNvpQKOwlkc25LbISbrdOOfY=
github.com/prometheus/common v0.44.0/go.mod h1:ofAIvZbQ1e/nugmZGz4/qCb9Ap1VoSTIO7x0VV9VvuY=
github.com/prometheus/procfs v0.11.1 h1:xRC8Iq1yyca5ypa9n1EZnWZkt7dwcoRPQwX/5gwaUuI=
github.com/prometheus/procfs v0.11.1/go.mod h1:eesXgaPo1q7lBpVMoMy0ZOFTth9hBn4W/y0/p/ScXhY=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.11.0 h1:eG7RXZHdqOJ1i+0lgLgCpSXAp6M3LYlAo6osgSi0xOM=
golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8=
google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
75 changes: 58 additions & 17 deletions player/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,30 +8,50 @@ import (
"os/exec"
"sync"
"time"

"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)

var (
mu sync.Mutex
previousID string
timeout = 8 * time.Second
timer *time.Timer
jsonData map[string]map[string]interface{}
isPlaying bool
mu sync.Mutex
lastPlayedID string
timeout = 3500 * time.Millisecond
timer *time.Timer
jsonData map[string]map[string]interface{}
isPlaying bool
)

// Define a Prometheus Counter to track the number of plays for each track ID.
var playsCounter = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "track_plays_total",
Help: "Total number of plays for each track ID.",
},
[]string{"track_id"},
)

type PostData struct {
ID string `json:"id"`
}

func playMP3(filePath string, offset int) {
if isPlaying {
fmt.Println("Music is already playing.")
func init() {
// Register the Prometheus metrics.
prometheus.MustRegister(playsCounter)
}

func playMP3(filePath string, offset int, currentID string) {
if isPlaying && currentID == lastPlayedID {
fmt.Println("This track is already playing.")
return
} else if isPlaying {
fmt.Println("Music is already playing, but starting new track.")
stopMP3()
}

isPlaying = true

cmd := exec.Command("mpg123", fmt.Sprintf("-k %d", offset), filePath)
cmd := exec.Command("mpg123", "-q", "-b", "512", fmt.Sprintf("-k %d", offset), filePath)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr

Expand All @@ -53,6 +73,7 @@ func stopMP3() {
if err != nil {
fmt.Println("Error stopping MP3:", err)
}
isPlaying = false
}
}

Expand All @@ -77,16 +98,30 @@ func playHandler(w http.ResponseWriter, r *http.Request) {
mu.Lock()
defer mu.Unlock()

if currentID == previousID {
fmt.Printf("Received the same ID again. Current ID: %s, Previous ID: %s\n", currentID, previousID)
// Reset the timer
if timer != nil {
timer.Stop()
// Check if something is playing now
if isPlaying {
if currentID != lastPlayedID {
// If something is already playing, and it's not the same as the incoming ID
fmt.Printf("Stopping the previous track (ID: %s) and starting the new track (ID: %s)\n", lastPlayedID, currentID)
stopMP3()
lastPlayedID = currentID
} else {
// If the same ID is requested again
fmt.Printf("Received the same ID again (ID: %s). Current track remains unchanged.\n", currentID)
// Reset the timer
if timer != nil {
timer.Stop()
}
}
} else {
previousID = currentID
// If nothing is playing, start playing the song
fmt.Printf("Starting to play the track (ID: %s)\n", currentID)
lastPlayedID = currentID
}

// Increment the playsCounter metric for the current track ID.
playsCounter.WithLabelValues(currentID).Inc()

// Start or reset the timer
if timer != nil {
timer.Stop()
Expand All @@ -105,7 +140,10 @@ func playHandler(w http.ResponseWriter, r *http.Request) {
filePath, _ := data["file"].(string)
offset, ok := data["offset"].(float64)
if ok {
playMP3("../"+filePath, int(offset))
if isPlaying == true {
fmt.Println("")
}
playMP3("../"+filePath, int(offset), currentID)
} else {
fmt.Println("Offset field not found in JSON for ID:", currentID)
}
Expand Down Expand Up @@ -143,6 +181,9 @@ func main() {
// Define the route and handler for /play
router.HandleFunc("/play", playHandler)

// Define a new route for Prometheus metrics
router.Handle("/metrics", promhttp.Handler())

// Create a handler chain with the request logger
chain := http.Handler(logRequest(router))

Expand Down

0 comments on commit 1be581e

Please sign in to comment.