server.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package server
  2. import (
  3. "fmt"
  4. "time"
  5. "github.com/gin-gonic/gin"
  6. "github.com/langgenius/dify-sandbox/internal/controller"
  7. "github.com/langgenius/dify-sandbox/internal/core/runner/python"
  8. "github.com/langgenius/dify-sandbox/internal/static"
  9. "github.com/langgenius/dify-sandbox/internal/utils/log"
  10. )
  11. func initConfig() {
  12. // auto migrate database
  13. err := static.InitConfig("conf/config.yaml")
  14. if err != nil {
  15. log.Panic("failed to init config: %v", err)
  16. }
  17. log.Info("config init success")
  18. err = static.SetupRunnerDependencies()
  19. if err != nil {
  20. log.Error("failed to setup runner dependencies: %v", err)
  21. }
  22. log.Info("runner dependencies init success")
  23. }
  24. func initServer() {
  25. config := static.GetDifySandboxGlobalConfigurations()
  26. if !config.App.Debug {
  27. gin.SetMode(gin.ReleaseMode)
  28. }
  29. r := gin.Default()
  30. r.Use(gin.Recovery())
  31. if gin.Mode() == gin.DebugMode {
  32. r.Use(gin.Logger())
  33. }
  34. controller.Setup(r)
  35. r.Run(fmt.Sprintf(":%d", config.App.Port))
  36. }
  37. func initDependencies() {
  38. log.Info("installing python dependencies...")
  39. dependencies := static.GetRunnerDependencies()
  40. err := python.InstallDependencies(dependencies.PythonRequirements)
  41. if err != nil {
  42. log.Panic("failed to install python dependencies: %v", err)
  43. }
  44. log.Info("python dependencies installed")
  45. log.Info("initializing python dependencies sandbox...")
  46. err = python.PreparePythonDependenciesEnv()
  47. if err != nil {
  48. log.Panic("failed to initialize python dependencies sandbox: %v", err)
  49. }
  50. log.Info("python dependencies sandbox initialized")
  51. // start a ticker to update python dependencies every 30 minutes to keep the sandbox up-to-date
  52. go func() {
  53. ticker := time.NewTicker(30 * time.Minute)
  54. for range ticker.C {
  55. log.Info("updating python dependencies...")
  56. err := python.InstallDependencies(dependencies.PythonRequirements)
  57. if err != nil {
  58. log.Error("failed to update python dependencies: %v", err)
  59. }
  60. err = python.PreparePythonDependenciesEnv()
  61. if err != nil {
  62. log.Error("failed to update python dependencies sandbox: %v", err)
  63. }
  64. log.Info("python dependencies updated")
  65. }
  66. }()
  67. }
  68. func Run() {
  69. // init config
  70. initConfig()
  71. // init dependencies, it will cost some times
  72. go initDependencies()
  73. initServer()
  74. }