server.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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. appImporter *services.AppImporter
  45. // Resource Handlers
  46. providerHandler *handlers.ProviderHandler
  47. // ticketHandler *handlers.TicketHandler
  48. stopped bool
  49. wg sync.WaitGroup
  50. // monitoringHandler *handlers.MonitoringHandler
  51. }
  52. func NewApp(cnf *config.Config) (*App, error) {
  53. ctx, cancelFunc := context.WithCancel(context.Background())
  54. app := &App{
  55. entry: logrus.WithField("component", "app"),
  56. cnf: cnf,
  57. ctx: ctx,
  58. cancelFunc: cancelFunc,
  59. }
  60. // Initialize router first
  61. if cnf.Debug {
  62. // gin.SetMode(gin.ReleaseMode)
  63. // gin.SetMode(gin.DebugMode)
  64. logrus.SetLevel(logrus.DebugLevel)
  65. } else {
  66. // Set gin to release mode for production
  67. // This will disable debug logs and enable performance optimizations
  68. gin.SetMode(gin.ReleaseMode)
  69. }
  70. app.rtr = gin.New()
  71. // Disable automatic redirection of trailing slashes
  72. // This prevents 301 redirects that can cause CORS issues
  73. app.rtr.RedirectTrailingSlash = false
  74. app.rtr.RedirectFixedPath = false
  75. app.rtr.Use(gin.Recovery())
  76. // app.rtr.Use(mw.Logger)
  77. // Add CORS middleware to handle cross-origin requests
  78. app.rtr.Use(mw.CORS())
  79. // Initialize clients
  80. app.buildkitClient = clients.NewDockerfileBuilder(cnf.BuildkitHost)
  81. app.entry.Info("Dockerfile builder client initialized")
  82. app.registryClient = clients.NewSimpleRegistryClient(app.buildkitClient)
  83. app.entry.Info("Registry client initialized")
  84. // Initialize services and handlers
  85. if err := app.initCommonServices(); err != nil {
  86. return nil, errors.Wrap(err, "initialize services")
  87. }
  88. if err := app.initHandlers(); err != nil {
  89. return nil, errors.Wrap(err, "initialize handlers")
  90. }
  91. // Set up routes after all handlers are initialized
  92. app.setupRoutes()
  93. return app, nil
  94. }
  95. // Shutdown gracefully shuts down the application and its resources.
  96. func (a *App) Shutdown(ctx context.Context) error {
  97. a.entry.Info("Initiating graceful shutdown...")
  98. // Signal all goroutines to stop
  99. a.cancelFunc() // This will close a.ctx
  100. // Close services
  101. if a.previewService != nil {
  102. a.entry.Info("Closing preview service...")
  103. a.previewService.Close(ctx) // Assuming Close() is idempotent or handles multiple calls gracefully
  104. a.entry.Info("Preview service closed.")
  105. }
  106. if a.tokenStore != nil {
  107. if closer, ok := a.tokenStore.(interface{ Close() error }); ok {
  108. a.entry.Info("Closing token store...")
  109. if err := closer.Close(); err != nil {
  110. a.entry.WithError(err).Error("Failed to close token store")
  111. // Potentially return this error or aggregate errors
  112. } else {
  113. a.entry.Info("Token store closed.")
  114. }
  115. }
  116. }
  117. // Close database connection
  118. if a.database != nil {
  119. a.entry.Info("Closing database connection...")
  120. if err := a.database.Close(); err != nil {
  121. a.entry.WithError(err).Error("Failed to close database connection")
  122. // Potentially return this error or aggregate errors
  123. } else {
  124. a.entry.Info("Database connection closed.")
  125. }
  126. }
  127. // Wait for any other background goroutines managed by the app to finish
  128. // a.wg.Wait() // Uncomment if you use sync.WaitGroup for other app-managed goroutines
  129. a.entry.Info("Graceful shutdown completed.")
  130. return nil
  131. }
  132. func (a *App) Run() error {
  133. // The main HTTP server instance for the application.
  134. // This will be shut down by the logic in main.go.
  135. srv := &http.Server{
  136. Addr: fmt.Sprintf(":%d", a.cnf.Server.Port),
  137. Handler: a.rtr,
  138. }
  139. // This goroutine will block until the server is shut down or an error occurs.
  140. // The actual shutdown signal is handled in main.go.
  141. go func() {
  142. select {
  143. case <-a.ctx.Done(): // Listen for the app context cancellation
  144. a.entry.Info("App context cancelled, initiating server shutdown from Run()...")
  145. // Context for server shutdown, can be different from app context if needed
  146. shutdownCtx, cancelShutdown := context.WithTimeout(context.Background(), 15*time.Second)
  147. defer cancelShutdown()
  148. if err := srv.Shutdown(shutdownCtx); err != nil {
  149. a.entry.WithError(err).Error("HTTP server shutdown error in Run() after context cancellation")
  150. }
  151. return
  152. }
  153. }()
  154. a.entry.WithField("address", srv.Addr).Infof("Starting server on port %d", a.cnf.Server.Port)
  155. var err error
  156. if a.cnf.Server.Tls.Enabled {
  157. a.entry.Info("Starting server with TLS...")
  158. err = srv.ListenAndServeTLS(a.cnf.Server.Tls.CertFile, a.cnf.Server.Tls.KeyFile)
  159. } else {
  160. a.entry.Info("Starting server without TLS...")
  161. err = srv.ListenAndServe()
  162. }
  163. if err != nil && err != http.ErrServerClosed {
  164. a.entry.WithError(err).Errorf("Server ListenAndServe error")
  165. return fmt.Errorf("failed to start server: %w", err)
  166. }
  167. a.entry.Info("Server Run() method finished.")
  168. return nil // http.ErrServerClosed is a normal error on shutdown
  169. }