server.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. package app
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "sync"
  7. "time"
  8. "git.linuxforward.com/byop/byop-engine/auth"
  9. "git.linuxforward.com/byop/byop-engine/clients"
  10. "git.linuxforward.com/byop/byop-engine/config"
  11. "git.linuxforward.com/byop/byop-engine/dbstore"
  12. "git.linuxforward.com/byop/byop-engine/handlers"
  13. mw "git.linuxforward.com/byop/byop-engine/middleware"
  14. "git.linuxforward.com/byop/byop-engine/services"
  15. "github.com/gin-gonic/gin"
  16. "github.com/pkg/errors"
  17. "github.com/sirupsen/logrus"
  18. )
  19. type App struct {
  20. entry *logrus.Entry
  21. cnf *config.Config
  22. ctx context.Context
  23. cancelFunc context.CancelFunc
  24. rtr *gin.Engine
  25. // Database
  26. database *dbstore.SQLiteStore
  27. // Services
  28. authService auth.Service
  29. tokenStore auth.TokenStore
  30. // Clients
  31. buildkitClient clients.BuildMachineClient // BuildKit client for build operations
  32. registryClient clients.RegistryClient // Docker registry client for pushing images
  33. // Handlers
  34. authHandler *handlers.AuthHandler
  35. userHandler *handlers.UserHandler
  36. clientHandler *handlers.ClientHandler
  37. componentHandler *handlers.ComponentHandler // Renamed from appHandler
  38. appHandler *handlers.AppsHandler // Renamed from templateHandler
  39. deploymentHandler *handlers.DeploymentHandler
  40. previewHandler *handlers.PreviewHandler
  41. // Preview Service
  42. previewService services.PreviewService
  43. builderService *services.Builder
  44. // Resource Handlers
  45. providerHandler *handlers.ProviderHandler
  46. // ticketHandler *handlers.TicketHandler
  47. stopped bool
  48. wg sync.WaitGroup
  49. // monitoringHandler *handlers.MonitoringHandler
  50. }
  51. func NewApp(cnf *config.Config) (*App, error) {
  52. ctx, cancelFunc := context.WithCancel(context.Background())
  53. app := &App{
  54. entry: logrus.WithField("component", "app"),
  55. cnf: cnf,
  56. ctx: ctx,
  57. cancelFunc: cancelFunc,
  58. }
  59. // Initialize router first
  60. if cnf.Debug {
  61. // gin.SetMode(gin.ReleaseMode)
  62. // gin.SetMode(gin.DebugMode)
  63. logrus.SetLevel(logrus.DebugLevel)
  64. } else {
  65. // Set gin to release mode for production
  66. // This will disable debug logs and enable performance optimizations
  67. gin.SetMode(gin.ReleaseMode)
  68. }
  69. app.rtr = gin.New()
  70. // Disable automatic redirection of trailing slashes
  71. // This prevents 301 redirects that can cause CORS issues
  72. app.rtr.RedirectTrailingSlash = false
  73. app.rtr.RedirectFixedPath = false
  74. app.rtr.Use(gin.Recovery())
  75. // app.rtr.Use(mw.Logger)
  76. // Add CORS middleware to handle cross-origin requests
  77. app.rtr.Use(mw.CORS())
  78. // Initialize clients
  79. app.buildkitClient = clients.NewDockerfileBuilder(cnf.BuildkitHost)
  80. app.entry.Info("Dockerfile builder client initialized")
  81. app.registryClient = clients.NewSimpleRegistryClient(app.buildkitClient)
  82. app.entry.Info("Registry client initialized")
  83. // Initialize services and handlers
  84. if err := app.initCommonServices(); err != nil {
  85. return nil, errors.Wrap(err, "initialize services")
  86. }
  87. if err := app.initHandlers(); err != nil {
  88. return nil, errors.Wrap(err, "initialize handlers")
  89. }
  90. // Set up routes after all handlers are initialized
  91. app.setupRoutes()
  92. return app, nil
  93. }
  94. // Shutdown gracefully shuts down the application and its resources.
  95. func (a *App) Shutdown(ctx context.Context) error {
  96. a.entry.Info("Initiating graceful shutdown...")
  97. // Signal all goroutines to stop
  98. a.cancelFunc() // This will close a.ctx
  99. // Close services
  100. if a.previewService != nil {
  101. a.entry.Info("Closing preview service...")
  102. a.previewService.Close(ctx) // Assuming Close() is idempotent or handles multiple calls gracefully
  103. a.entry.Info("Preview service closed.")
  104. }
  105. if a.tokenStore != nil {
  106. if closer, ok := a.tokenStore.(interface{ Close() error }); ok {
  107. a.entry.Info("Closing token store...")
  108. if err := closer.Close(); err != nil {
  109. a.entry.WithError(err).Error("Failed to close token store")
  110. // Potentially return this error or aggregate errors
  111. } else {
  112. a.entry.Info("Token store closed.")
  113. }
  114. }
  115. }
  116. // Close database connection
  117. if a.database != nil {
  118. a.entry.Info("Closing database connection...")
  119. if err := a.database.Close(); err != nil {
  120. a.entry.WithError(err).Error("Failed to close database connection")
  121. // Potentially return this error or aggregate errors
  122. } else {
  123. a.entry.Info("Database connection closed.")
  124. }
  125. }
  126. // Wait for any other background goroutines managed by the app to finish
  127. // a.wg.Wait() // Uncomment if you use sync.WaitGroup for other app-managed goroutines
  128. a.entry.Info("Graceful shutdown completed.")
  129. return nil
  130. }
  131. func (a *App) Run() error {
  132. // The main HTTP server instance for the application.
  133. // This will be shut down by the logic in main.go.
  134. srv := &http.Server{
  135. Addr: fmt.Sprintf(":%d", a.cnf.Server.Port),
  136. Handler: a.rtr,
  137. }
  138. // This goroutine will block until the server is shut down or an error occurs.
  139. // The actual shutdown signal is handled in main.go.
  140. go func() {
  141. select {
  142. case <-a.ctx.Done(): // Listen for the app context cancellation
  143. a.entry.Info("App context cancelled, initiating server shutdown from Run()...")
  144. // Context for server shutdown, can be different from app context if needed
  145. shutdownCtx, cancelShutdown := context.WithTimeout(context.Background(), 15*time.Second)
  146. defer cancelShutdown()
  147. if err := srv.Shutdown(shutdownCtx); err != nil {
  148. a.entry.WithError(err).Error("HTTP server shutdown error in Run() after context cancellation")
  149. }
  150. return
  151. }
  152. }()
  153. a.entry.WithField("address", srv.Addr).Infof("Starting server on port %d", a.cnf.Server.Port)
  154. var err error
  155. if a.cnf.Server.Tls.Enabled {
  156. a.entry.Info("Starting server with TLS...")
  157. err = srv.ListenAndServeTLS(a.cnf.Server.Tls.CertFile, a.cnf.Server.Tls.KeyFile)
  158. } else {
  159. a.entry.Info("Starting server without TLS...")
  160. err = srv.ListenAndServe()
  161. }
  162. if err != nil && err != http.ErrServerClosed {
  163. a.entry.WithError(err).Errorf("Server ListenAndServe error")
  164. return fmt.Errorf("failed to start server: %w", err)
  165. }
  166. a.entry.Info("Server Run() method finished.")
  167. return nil // http.ErrServerClosed is a normal error on shutdown
  168. }