setup.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package python
  2. import (
  3. _ "embed"
  4. "os"
  5. "os/exec"
  6. "path"
  7. "github.com/langgenius/dify-sandbox/internal/core/runner"
  8. python_dependencies "github.com/langgenius/dify-sandbox/internal/core/runner/python/dependencies"
  9. "github.com/langgenius/dify-sandbox/internal/core/runner/types"
  10. "github.com/langgenius/dify-sandbox/internal/utils/log"
  11. )
  12. //go:embed python.so
  13. var python_lib []byte
  14. func init() {
  15. log.Info("initializing python runner environment...")
  16. // remove /tmp/sandbox-python
  17. os.RemoveAll("/tmp/sandbox-python")
  18. os.Remove("/tmp/sandbox-python")
  19. err := os.MkdirAll("/tmp/sandbox-python", 0755)
  20. if err != nil {
  21. log.Panic("failed to create /tmp/sandbox-python")
  22. }
  23. err = os.WriteFile("/tmp/sandbox-python/python.so", python_lib, 0755)
  24. if err != nil {
  25. log.Panic("failed to write /tmp/sandbox-python/python.so")
  26. }
  27. log.Info("python runner environment initialized")
  28. }
  29. func InstallDependencies(requirements string) error {
  30. if requirements == "" {
  31. return nil
  32. }
  33. runner := runner.TempDirRunner{}
  34. return runner.WithTempDir([]string{}, func(root_path string) error {
  35. // create a requirements file
  36. err := os.WriteFile(path.Join(root_path, "requirements.txt"), []byte(requirements), 0644)
  37. if err != nil {
  38. log.Panic("failed to create requirements.txt")
  39. }
  40. // install dependencies
  41. cmd := exec.Command("pip3", "install", "-r", "requirements.txt")
  42. reader, err := cmd.StdoutPipe()
  43. if err != nil {
  44. log.Panic("failed to get stdout pipe of pip3")
  45. }
  46. defer reader.Close()
  47. err = cmd.Start()
  48. if err != nil {
  49. log.Panic("failed to start pip3")
  50. }
  51. defer cmd.Wait()
  52. for {
  53. buf := make([]byte, 1024)
  54. n, err := reader.Read(buf)
  55. if err != nil {
  56. break
  57. }
  58. log.Info(string(buf[:n]))
  59. }
  60. return nil
  61. })
  62. }
  63. func ListDependencies() []types.Dependency {
  64. return python_dependencies.ListDependencies()
  65. }