lifetime.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. log.Info("new plugin logged in: %s", configuration.Identity())
  12. defer log.Info("plugin %s has exited", configuration.Identity())
  13. // store plugin runtime
  14. m.Store(configuration.Identity(), r)
  15. defer m.Delete(configuration.Identity())
  16. // update lifetime state for this pod
  17. addLifetimeState(r)
  18. // remove lifetime state after plugin if it has been stopped
  19. defer deleteLifetimeState(r)
  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. if r.Stopped() {
  38. break
  39. }
  40. log.Error("start plugin failed: %s, retry in 30s", err.Error())
  41. time.Sleep(30 * time.Second)
  42. if start_failed_times == 3 {
  43. log.Error(
  44. "start plugin failed 3 times, plugin %s has been stopped",
  45. configuration.Identity(),
  46. )
  47. r.Stop()
  48. }
  49. start_failed_times++
  50. continue
  51. }
  52. // wait for plugin to stop
  53. c, err := r.Wait()
  54. if err == nil {
  55. <-c
  56. }
  57. // restart plugin in 5s
  58. time.Sleep(5 * time.Second)
  59. }
  60. }