lifetime.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 (p *PluginManager) 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. // add plugin to cluster
  14. err := p.cluster.RegisterPlugin(r)
  15. if err != nil {
  16. log.Error("add plugin to cluster failed: %s", err.Error())
  17. return
  18. }
  19. // remove lifetime state after plugin if it has been stopped
  20. defer r.TriggerStop()
  21. for !r.Stopped() {
  22. if err := r.InitEnvironment(); err != nil {
  23. log.Error("init environment failed: %s, retry in 30s", err.Error())
  24. time.Sleep(30 * time.Second)
  25. if start_failed_times == 3 {
  26. log.Error(
  27. "init environment failed 3 times, plugin %s has been stopped",
  28. configuration.Identity(),
  29. )
  30. r.Stop()
  31. }
  32. start_failed_times++
  33. continue
  34. }
  35. start_failed_times = 0
  36. // start plugin
  37. if err := r.StartPlugin(); err != nil {
  38. if r.Stopped() {
  39. break
  40. }
  41. log.Error("start plugin failed: %s, retry in 30s", err.Error())
  42. time.Sleep(30 * time.Second)
  43. if start_failed_times == 3 {
  44. log.Error(
  45. "start plugin failed 3 times, plugin %s has been stopped",
  46. configuration.Identity(),
  47. )
  48. r.Stop()
  49. }
  50. start_failed_times++
  51. continue
  52. }
  53. // wait for plugin to stop
  54. c, err := r.Wait()
  55. if err == nil {
  56. <-c
  57. }
  58. // restart plugin in 5s
  59. time.Sleep(5 * time.Second)
  60. // add restart times
  61. state := r.RuntimeState()
  62. state.Restarts++
  63. r.UpdateState(state)
  64. }
  65. }