Skip to content

Commit

Permalink
pprof
Browse files Browse the repository at this point in the history
  • Loading branch information
candiduslynx committed May 11, 2024
1 parent 50c6f1f commit 0cd1d4a
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 1 deletion.
5 changes: 4 additions & 1 deletion plugins/destination/postgresql/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,11 @@ func main() {
serve.WithPluginSentryDSN(sentryDSN),
serve.WithDestinationV0V1Server(),
)

done := instrumentPprof()
defer done()
err := server.Serve(context.Background())
if err != nil {
log.Fatalf("failed to serve plugin: %v", err)
log.Println("failed to serve plugin:", err)
}
}
56 changes: 56 additions & 0 deletions plugins/destination/postgresql/pprof.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package main

import (
"fmt"
"log"
"os"
"runtime"
"runtime/pprof"
)

const (
PProfHeapFile = "PPROF_HEAP_FILE"
PProfCPUFile = "PPROF_CPU_FILE"
)

func instrumentPprof() func() {
heapFile := createProfileFile(os.Getenv(PProfHeapFile))
cpuFile := createProfileFile(os.Getenv(PProfCPUFile))
if cpuFile != nil {
if err := pprof.StartCPUProfile(cpuFile); err != nil {
log.Fatal("could not start CPU profile: ", err)
}
}

return func() {
if cpuFile != nil {
pprof.StopCPUProfile()
if err := cpuFile.Close(); err != nil {
fmt.Printf("failed to close CPU profile: %v\n", err)
}
}
if heapFile != nil {
// get up-to-date statistics
runtime.GC() // nolint:revive
if err := pprof.WriteHeapProfile(heapFile); err != nil {
log.Fatal("could not write memory profile: ", err)
}
if err := heapFile.Close(); err != nil {
fmt.Printf("failed to close heap profile: %v\n", err)
}
}
}
}

func createProfileFile(path string) *os.File {
if path == "" {
return nil
}

f, err := os.Create(path)
if err != nil {
log.Fatalf("failed to create %q file for profile: %v", path, err)
}

return f
}

0 comments on commit 0cd1d4a

Please sign in to comment.