/cmd/root.go

https://github.com/stephenafamo/docker-nginx-auto-proxy · Go · 98 lines · 80 code · 14 blank · 4 comment · 16 complexity · 97f73dc54b72ee7743057556e68562eb MD5 · raw file

  1. package cmd
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "log"
  6. "os"
  7. "os/exec"
  8. "path/filepath"
  9. "syscall"
  10. "time"
  11. "github.com/spf13/cobra"
  12. "github.com/stephenafamo/orchestra"
  13. "github.com/stephenafamo/warden/internal"
  14. )
  15. // Execute adds all child commands to the root command and sets flags appropriately.
  16. // This is called by main.main(). It only needs to happen once to the rootCmd.
  17. func Execute(settings internal.Settings) {
  18. // rootCmd represents the base command when called without any subcommands
  19. var rootCmd = &cobra.Command{
  20. Use: "warden",
  21. Short: "Setup and manage a reverse proxy",
  22. Long: "Setup and manage a reverse proxy",
  23. RunE: func(cmd *cobra.Command, args []string) error {
  24. log.Println("Cleaning up...")
  25. c := exec.Command(
  26. "/bin/sh",
  27. "-c",
  28. fmt.Sprintf(
  29. "rm -rf %s %s",
  30. filepath.Join(settings.CONFIG_OUTPUT_DIR, "/http/*"),
  31. filepath.Join(settings.CONFIG_OUTPUT_DIR, "/streams/*"),
  32. ),
  33. )
  34. output, err := c.CombinedOutput()
  35. if err != nil {
  36. return fmt.Errorf(
  37. "Error cleaning up: %s: %s",
  38. err,
  39. output,
  40. )
  41. }
  42. log.Println("Connecting to DB...")
  43. db, err := sql.Open("sqlite3", "file::memory:?_fk=1&cache=shared&mode=memory")
  44. if err != nil {
  45. return err
  46. }
  47. db.SetMaxOpenConns(1)
  48. defer db.Close()
  49. log.Println("Creating tables...")
  50. err = createTables(db)
  51. if err != nil {
  52. return err
  53. }
  54. conductor := &orchestra.Conductor{
  55. Timeout: 15 * time.Second,
  56. Players: make(map[string]orchestra.Player),
  57. }
  58. hub, err := getMonitor(settings)
  59. if err != nil {
  60. return fmt.Errorf("could not get monitor: %w", err)
  61. }
  62. defer hub.Flush(time.Second * 5)
  63. allPlayers, err := setPlayers(db, settings, hub)
  64. if err != nil {
  65. return fmt.Errorf("could not get players: %w", err)
  66. }
  67. // Start all if no args were given
  68. if len(args) == 0 {
  69. conductor.Players = allPlayers
  70. }
  71. for _, pl := range args {
  72. player, ok := allPlayers[pl]
  73. if ok {
  74. conductor.Players[pl] = player
  75. }
  76. }
  77. return orchestra.PlayUntilSignal(
  78. conductor,
  79. os.Interrupt, syscall.SIGTERM,
  80. )
  81. },
  82. }
  83. rootCmd.Execute()
  84. }