apollo-backend/internal/cmd/root.go

66 lines
1.2 KiB
Go
Raw Permalink Normal View History

package cmd
import (
"context"
2021-07-16 00:09:38 +00:00
"os"
2021-07-16 00:50:04 +00:00
"runtime"
2021-07-16 00:09:38 +00:00
"runtime/pprof"
2021-07-13 19:35:46 +00:00
_ "github.com/heroku/x/hmetrics/onload"
"github.com/joho/godotenv"
"github.com/spf13/cobra"
)
func Execute(ctx context.Context) int {
_ = godotenv.Load()
2021-07-16 00:09:38 +00:00
profile := false
rootCmd := &cobra.Command{
Use: "apollo",
Short: "Apollo is an amazing Reddit client for iOS. This isn't it, but it helps.",
2021-07-16 00:09:38 +00:00
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
if !profile {
return nil
}
2021-07-16 00:50:04 +00:00
2021-07-16 00:09:38 +00:00
f, perr := os.Create("cpu.pprof")
if perr != nil {
return perr
}
2021-07-16 00:50:04 +00:00
2021-09-25 13:19:42 +00:00
_ = pprof.StartCPUProfile(f)
2021-07-16 00:09:38 +00:00
return nil
},
2021-07-16 00:50:04 +00:00
PersistentPostRunE: func(cmd *cobra.Command, args []string) error {
if !profile {
return nil
}
pprof.StopCPUProfile()
f, perr := os.Create("mem.pprof")
if perr != nil {
return perr
2021-07-16 00:09:38 +00:00
}
2021-07-16 00:50:04 +00:00
defer f.Close()
runtime.GC()
err := pprof.WriteHeapProfile(f)
return err
2021-07-16 00:09:38 +00:00
},
}
2021-07-16 00:09:38 +00:00
rootCmd.PersistentFlags().BoolVarP(&profile, "profile", "p", false, "record CPU pprof")
rootCmd.AddCommand(APICmd(ctx))
rootCmd.AddCommand(SchedulerCmd(ctx))
rootCmd.AddCommand(WorkerCmd(ctx))
if err := rootCmd.Execute(); err != nil {
return 1
}
return 0
}