Skip to content

Commit

Permalink
Add __session_id__ label (#52)
Browse files Browse the repository at this point in the history
  • Loading branch information
kolesnikovae authored Oct 4, 2023
1 parent af608b5 commit c0ec465
Showing 1 changed file with 62 additions and 2 deletions.
64 changes: 62 additions & 2 deletions session.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@ package pyroscope

import (
"bytes"
crand "crypto/rand"
"encoding/binary"
"encoding/hex"
"hash/fnv"
"math/rand"
"os"
"runtime"
"runtime/debug"
"runtime/pprof"
Expand Down Expand Up @@ -112,7 +118,7 @@ type flush struct {
}

func NewSession(c SessionConfig) (*Session, error) {
appName, err := mergeTagsWithAppName(c.AppName, c.Tags)
appName, err := mergeTagsWithAppName(c.AppName, newSessionID(), c.Tags)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -151,7 +157,7 @@ func NewSession(c SessionConfig) (*Session, error) {
//
// App name may be an empty string. Tags must not contain reserved keys,
// the map is modified in place.
func mergeTagsWithAppName(appName string, tags map[string]string) (string, error) {
func mergeTagsWithAppName(appName string, sid sessionID, tags map[string]string) (string, error) {
k, err := flameql.ParseKey(appName)
if err != nil {
return "", err
Expand All @@ -165,6 +171,7 @@ func mergeTagsWithAppName(appName string, tags map[string]string) (string, error
}
k.Add(tagKey, tagValue)
}
k.Add(sessionIDLabelName, sid.String())
return k.Normalized(), nil
}

Expand Down Expand Up @@ -452,3 +459,56 @@ func numGC() uint32 {
runtime.ReadMemStats(&memStats)
return memStats.NumGC
}

const sessionIDLabelName = "__session_id__"

type sessionID uint64

func (s sessionID) String() string {
var b [8]byte
binary.LittleEndian.PutUint64(b[:], uint64(s))
return hex.EncodeToString(b[:])
}

func newSessionID() sessionID { return globalSessionIDGenerator.newSessionID() }

var globalSessionIDGenerator = newSessionIDGenerator()

type sessionIDGenerator struct {
sync.Mutex
src *rand.Rand
}

func (gen *sessionIDGenerator) newSessionID() sessionID {
var b [8]byte
gen.Lock()
_, _ = gen.src.Read(b[:])
gen.Unlock()
return sessionID(binary.LittleEndian.Uint64(b[:]))
}

func newSessionIDGenerator() *sessionIDGenerator {
s, ok := sessionIDHostSeed()
if !ok {
s = sessionIDRandSeed()
}
return &sessionIDGenerator{src: rand.New(rand.NewSource(s))}
}

func sessionIDRandSeed() int64 {
var rndSeed int64
_ = binary.Read(crand.Reader, binary.LittleEndian, &rndSeed)
return rndSeed
}

var hostname = os.Hostname

func sessionIDHostSeed() (int64, bool) {
v, err := hostname()
if err != nil {
return 0, false
}
h := fnv.New64a()
_, _ = h.Write([]byte(v))
return int64(h.Sum64()), true
}

0 comments on commit c0ec465

Please sign in to comment.