Skip to content
Open
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
5 changes: 5 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
.git
bin/
tmp/
examples/
mixin/
20 changes: 20 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
FROM --platform=$BUILDPLATFORM golang:1.23-alpine AS build
RUN apk --update --no-cache add git
WORKDIR /src
COPY go.mod go.sum ./
COPY vendor ./vendor
COPY cmd ./cmd
COPY pkg ./pkg
ARG TARGETOS=linux
ARG TARGETARCH
ARG VERSION
ARG GIT_REVISION
ARG GIT_BRANCH
RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -mod vendor \
-ldflags "-X main.Branch=${GIT_BRANCH} -X main.Revision=${GIT_REVISION} -X main.Version=${VERSION}" \
-o /out/prometheus-plex-exporter ./cmd/prometheus-plex-exporter

FROM alpine:3.16 AS certs
RUN apk --update --no-cache add ca-certificates tzdata
COPY --from=build /out/prometheus-plex-exporter /prometheus-plex-exporter
ENTRYPOINT ["/prometheus-plex-exporter"]
9 changes: 7 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,13 @@ exe:
### Docker Images

.PHONY: docker-component # Not intended to be used directly
docker-component: check-component exe
docker build -t jsclayton/$(COMPONENT) --build-arg=TARGETARCH=$(GOARCH) -f ./cmd/$(COMPONENT)/Dockerfile .
docker-component: check-component
docker build -t jsclayton/$(COMPONENT) \
--build-arg=TARGETARCH=$(GOARCH) \
--build-arg=VERSION=$(VERSION) \
--build-arg=GIT_REVISION=$(GIT_REVISION) \
--build-arg=GIT_BRANCH=$(GIT_BRANCH) \
-f ./Dockerfile .
docker tag jsclayton/$(COMPONENT) $(COMPONENT)
docker tag jsclayton/$(COMPONENT) ghcr.io/jsclayton/$(COMPONENT):latest
docker tag jsclayton/$(COMPONENT) ghcr.io/jsclayton/$(COMPONENT):main
Expand Down
5 changes: 0 additions & 5 deletions cmd/prometheus-plex-exporter/Dockerfile

This file was deleted.

8 changes: 7 additions & 1 deletion pkg/plex/listener.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ func (s *Server) Listen(ctx context.Context, log log.Logger) error {
s.listener = &plexListener{
server: s,
conn: conn,
activeSessions: NewSessions(ctx, s),
activeSessions: NewSessions(ctx, s, conn.GetSessions),
log: log,
}

Expand Down Expand Up @@ -105,6 +105,12 @@ func (l *plexListener) onPlaying(c plex.NotificationContainer) error {
return fmt.Errorf("error fetching sessions: %w", err)
}

liveSessionKeys := make(map[string]struct{}, len(sessions.MediaContainer.Metadata))
for _, session := range sessions.MediaContainer.Metadata {
liveSessionKeys[session.SessionKey] = struct{}{}
}
l.activeSessions.ReconcileActive(liveSessionKeys)

for _, n := range c.PlaySessionStateNotification {
if sessionState(n.State) == stateStopped {
// When the session is stopped we can't look up the user info or media anymore.
Expand Down
44 changes: 43 additions & 1 deletion pkg/plex/sessions.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ type sessions struct {
totalEstimatedTransmittedKBits float64
}

func NewSessions(ctx context.Context, server *Server) *sessions {
func NewSessions(ctx context.Context, server *Server, pollSessions func() (plex.CurrentSessions, error)) *sessions {
s := &sessions{
sessions: map[string]session{},
server: server,
Expand All @@ -56,6 +56,7 @@ func NewSessions(ctx context.Context, server *Server) *sessions {
select {
case <-ticker.C:
s.pruneOldSessions()
s.reconcileFromLive(pollSessions)
case <-ctx.Done():
ticker.Stop()
return
Expand All @@ -66,6 +67,24 @@ func NewSessions(ctx context.Context, server *Server) *sessions {
return s
}

func (s *sessions) reconcileFromLive(pollSessions func() (plex.CurrentSessions, error)) {
if pollSessions == nil {
return
}

live, err := pollSessions()
if err != nil {
return
}

liveSessionKeys := make(map[string]struct{}, len(live.MediaContainer.Metadata))
for _, session := range live.MediaContainer.Metadata {
liveSessionKeys[session.SessionKey] = struct{}{}
}

s.ReconcileActive(liveSessionKeys)
}

func (s *sessions) pruneOldSessions() {
s.mtx.Lock()
defer s.mtx.Unlock()
Expand All @@ -77,6 +96,29 @@ func (s *sessions) pruneOldSessions() {
}
}

func (s *sessions) ReconcileActive(liveSessionKeys map[string]struct{}) {
s.mtx.Lock()
defer s.mtx.Unlock()

for id, ss := range s.sessions {
if ss.state == stateStopped {
continue
}
if _, ok := liveSessionKeys[id]; ok {
continue
}

if ss.state == statePlaying {
ss.prevPlayedTime += time.Since(ss.playStarted)
s.totalEstimatedTransmittedKBits += time.Since(ss.playStarted).Seconds() * float64(ss.session.Media[0].Bitrate)
}

ss.state = stateStopped
ss.lastUpdate = time.Now()
s.sessions[id] = ss
}
}

func (s *sessions) Update(sessionID string, newState sessionState, newSession *plex.Metadata, media *plex.Metadata) {
s.mtx.Lock()
defer s.mtx.Unlock()
Expand Down
66 changes: 66 additions & 0 deletions pkg/plex/sessions_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package plex

import (
"context"
"testing"

"github.com/jrudio/go-plex-client"
)

func newTestSessions() *sessions {
return NewSessions(context.Background(), &Server{ID: "test", Name: "test"}, nil)
}

func metadataWithBitrate(bitrate int) *plex.Metadata {
return &plex.Metadata{
Media: []plex.Media{
{Bitrate: bitrate},
},
}
}

func TestReconcileActive_StopsMissingSessions(t *testing.T) {
s := newTestSessions()

s.Update("abc123", statePlaying, metadataWithBitrate(1000), metadataWithBitrate(1000))

if got := s.sessions["abc123"].state; got != statePlaying {
t.Fatalf("expected session to be playing after Update, got %v", got)
}

s.ReconcileActive(map[string]struct{}{})

if got := s.sessions["abc123"].state; got != stateStopped {
t.Fatalf("expected session to be stopped after reconcile, got %v", got)
}
}

func TestReconcileActive_LeavesLiveSessionsAlone(t *testing.T) {
s := newTestSessions()

s.Update("abc123", statePlaying, metadataWithBitrate(1000), metadataWithBitrate(1000))

s.ReconcileActive(map[string]struct{}{"abc123": {}})

if got := s.sessions["abc123"].state; got != statePlaying {
t.Fatalf("expected session to remain playing, got %v", got)
}
}

func TestReconcileActive_AlreadyStoppedUntouched(t *testing.T) {
s := newTestSessions()

s.Update("abc123", statePlaying, metadataWithBitrate(1000), metadataWithBitrate(1000))
s.Update("abc123", stateStopped, nil, nil)

before := s.totalEstimatedTransmittedKBits

s.ReconcileActive(map[string]struct{}{})

if got := s.sessions["abc123"].state; got != stateStopped {
t.Fatalf("expected session to remain stopped, got %v", got)
}
if s.totalEstimatedTransmittedKBits != before {
t.Fatalf("expected totalEstimatedTransmittedKBits to be unchanged, got %v want %v", s.totalEstimatedTransmittedKBits, before)
}
}
Loading