lifetime.go 1.6 KB

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