lifetime.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package plugin_manager
  2. import (
  3. "time"
  4. "github.com/langgenius/dify-plugin-daemon/internal/types/app"
  5. "github.com/langgenius/dify-plugin-daemon/internal/types/entities"
  6. "github.com/langgenius/dify-plugin-daemon/internal/utils/log"
  7. )
  8. func lifetime(config *app.Config, r entities.PluginRuntimeInterface) {
  9. start_failed_times := 0
  10. configuration := r.Configuration()
  11. addLifetimeState(r)
  12. defer func() {
  13. // remove lifetime state after plugin if it has been stopped for $LIFETIME_STATE_GC_INTERVAL and not started again
  14. time.AfterFunc(time.Duration(config.LifetimeStateGCInterval)*time.Second, func() {
  15. if r.Stopped() {
  16. deleteLifetimeState(r)
  17. }
  18. })
  19. }()
  20. for !r.Stopped() {
  21. if err := r.InitEnvironment(); err != nil {
  22. log.Error("init environment failed: %s, retry in 30s", err.Error())
  23. time.Sleep(30 * time.Second)
  24. if start_failed_times == 3 {
  25. log.Error(
  26. "init environment failed 3 times, plugin %s has been stopped",
  27. configuration.Identity(),
  28. )
  29. r.Stop()
  30. }
  31. start_failed_times++
  32. continue
  33. }
  34. start_failed_times = 0
  35. // start plugin
  36. if err := r.StartPlugin(); err != nil {
  37. log.Error("start plugin failed: %s, retry in 30s", err.Error())
  38. time.Sleep(30 * time.Second)
  39. if start_failed_times == 3 {
  40. log.Error(
  41. "start plugin failed 3 times, plugin %s has been stopped",
  42. configuration.Identity(),
  43. )
  44. r.Stop()
  45. }
  46. start_failed_times++
  47. continue
  48. }
  49. // wait for plugin to stop
  50. c, err := r.Wait()
  51. if err == nil {
  52. <-c
  53. }
  54. // restart plugin in 5s
  55. time.Sleep(5 * time.Second)
  56. }
  57. }