You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
1.3 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. package services
  2. import (
  3. "context"
  4. "git.aiterp.net/lucifer/new-server/app/config"
  5. "git.aiterp.net/lucifer/new-server/models"
  6. "log"
  7. "sync"
  8. "time"
  9. )
  10. var cancelMap = make(map[int]context.CancelFunc, 8)
  11. var cancelMutex sync.Mutex
  12. func ConnectToBridges() {
  13. go func() {
  14. for {
  15. err := runConnectToBridges()
  16. if err != nil {
  17. log.Println("Bridge connection error: ", err.Error())
  18. }
  19. time.Sleep(15 * time.Second)
  20. }
  21. }()
  22. }
  23. func runConnectToBridges() error {
  24. bridges, err := config.BridgeRepository().FetchAll(context.Background())
  25. if err != nil {
  26. return err
  27. }
  28. for _, bridge := range bridges {
  29. cancelMutex.Lock()
  30. isRunning := cancelMap[bridge.ID] != nil
  31. cancelMutex.Unlock()
  32. if isRunning {
  33. continue
  34. }
  35. driver, err := config.DriverProvider().Provide(bridge.Driver)
  36. if err != nil {
  37. return err
  38. }
  39. ctx, cancel := context.WithCancel(context.Background())
  40. cancelMutex.Lock()
  41. cancelMap[bridge.ID] = cancel
  42. cancelMutex.Unlock()
  43. log.Printf("Running bridge \"%s\" (%d)", bridge.Name, bridge.ID)
  44. go func(bridge models.Bridge, cancel func()) {
  45. err = driver.Run(ctx, bridge, config.EventChannel)
  46. log.Printf("Bridge \"%s\" (%d) stopped: %s", bridge.Name, bridge.ID, err)
  47. cancelMutex.Lock()
  48. cancel()
  49. cancelMap[bridge.ID] = nil
  50. cancelMutex.Unlock()
  51. }(bridge, cancel)
  52. }
  53. return nil
  54. }