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. // store plugin runtime
  12. m.Store(configuration.Identity(), r)
  13. defer m.Delete(configuration.Identity())
  14. // update lifetime state for this pod
  15. addLifetimeState(r)
  16. // remove lifetime state after plugin if it has been stopped
  17. defer deleteLifetimeState(r)
  18. for !r.Stopped() {
  19. if err := r.InitEnvironment(); err != nil {
  20. log.Error("init environment failed: %s, retry in 30s", err.Error())
  21. time.Sleep(30 * time.Second)
  22. if start_failed_times == 3 {
  23. log.Error(
  24. "init environment failed 3 times, plugin %s has been stopped",
  25. configuration.Identity(),
  26. )
  27. r.Stop()
  28. }
  29. start_failed_times++
  30. continue
  31. }
  32. start_failed_times = 0
  33. // start plugin
  34. if err := r.StartPlugin(); err != nil {
  35. log.Error("start plugin failed: %s, retry in 30s", err.Error())
  36. time.Sleep(30 * time.Second)
  37. if start_failed_times == 3 {
  38. log.Error(
  39. "start plugin failed 3 times, plugin %s has been stopped",
  40. configuration.Identity(),
  41. )
  42. r.Stop()
  43. }
  44. start_failed_times++
  45. continue
  46. }
  47. // wait for plugin to stop
  48. c, err := r.Wait()
  49. if err == nil {
  50. <-c
  51. }
  52. // restart plugin in 5s
  53. time.Sleep(5 * time.Second)
  54. }
  55. }