hashedworkermanager.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package appsrv
  15. import (
  16. "fmt"
  17. "github.com/serialx/hashring"
  18. "yunion.io/x/pkg/util/stringutils"
  19. )
  20. type SHashedWorkerManager struct {
  21. workers []*SWorkerManager
  22. workerRing *hashring.HashRing
  23. indexMap map[string]int
  24. }
  25. func NewHashWorkerManager(name string, workerCount int, subWorkerCnt int, backlog int, dbWorker bool) *SHashedWorkerManager {
  26. workers := make([]*SWorkerManager, workerCount)
  27. syncWorkerIndexes := make([]string, workerCount)
  28. indexMap := map[string]int{}
  29. for i := range workers {
  30. workers[i] = NewWorkerManager(
  31. fmt.Sprintf("%s-%d", name, i+1),
  32. subWorkerCnt,
  33. backlog,
  34. dbWorker,
  35. )
  36. syncWorkerIndexes[i] = stringutils.UUID4()
  37. indexMap[syncWorkerIndexes[i]] = i
  38. }
  39. workerRing := hashring.New(syncWorkerIndexes)
  40. return &SHashedWorkerManager{
  41. workers: workers,
  42. workerRing: workerRing,
  43. indexMap: indexMap,
  44. }
  45. }
  46. func (man *SHashedWorkerManager) GetWorkerManager(key string) *SWorkerManager {
  47. nodeIdxStr, _ := man.workerRing.GetNode(key)
  48. return man.workers[man.indexMap[nodeIdxStr]]
  49. }