apollo-backend/internal/cmd/root.go

82 lines
1.6 KiB
Go
Raw Permalink Normal View History

package cmd
import (
"context"
2022-08-08 16:48:34 +00:00
"net/http"
_ "net/http/pprof"
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"
2022-03-28 17:20:01 +00:00
"github.com/bugsnag/bugsnag-go/v2"
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()
2022-03-28 17:23:24 +00:00
if key, ok := os.LookupEnv("BUGSNAG_API_KEY"); ok {
2022-03-28 17:20:01 +00:00
bugsnag.Configure(bugsnag.Configuration{
APIKey: key,
ReleaseStage: os.Getenv("ENV"),
ProjectPackages: []string{"main", "github.com/christianselig/apollo-backend"},
2022-03-28 17:50:06 +00:00
AppVersion: os.Getenv("RENDER_GIT_COMMIT"),
2022-03-28 17:20:01 +00:00
})
}
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))
2022-08-08 16:48:34 +00:00
go func() {
_ = http.ListenAndServe("localhost:6060", nil)
}()
if err := rootCmd.Execute(); err != nil {
return 1
}
return 0
}