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

consistent_hash_ring.cc 2.0 kB

4 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /**
  2. * Copyright 2021 Huawei Technologies Co., Ltd
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "fl/server/consistent_hash_ring.h"
  17. namespace mindspore {
  18. namespace fl {
  19. namespace server {
  20. bool ConsistentHashRing::Insert(uint32_t rank) {
  21. for (uint32_t i = 0; i < virtual_node_num_; i++) {
  22. std::string physical_node_hash_key = std::to_string(rank) + "#" + std::to_string(i);
  23. size_t hash_value = std::hash<std::string>()(physical_node_hash_key);
  24. MS_LOG(DEBUG) << "Insert virtual node " << physical_node_hash_key << " for node " << rank << ", hash value is "
  25. << hash_value;
  26. if (ring_.count(hash_value) != 0) {
  27. MS_LOG(WARNING) << "Virtual node " << physical_node_hash_key << " is already mapped to the ring.";
  28. continue;
  29. }
  30. ring_[hash_value] = rank;
  31. }
  32. return true;
  33. }
  34. bool ConsistentHashRing::Erase(uint32_t rank) {
  35. for (auto iterator = ring_.begin(); iterator != ring_.end();) {
  36. if (iterator->second == rank) {
  37. (void)ring_.erase(iterator++);
  38. } else {
  39. ++iterator;
  40. }
  41. }
  42. return true;
  43. }
  44. uint32_t ConsistentHashRing::Find(const std::string &key) {
  45. size_t hash_value = std::hash<std::string>()(key);
  46. auto iterator = ring_.lower_bound(hash_value);
  47. if (iterator == ring_.end()) {
  48. // If the virtual node is not found clockwise, the key will be mapped to the first virtual node on the ring.
  49. iterator = ring_.begin();
  50. }
  51. return iterator->second;
  52. }
  53. } // namespace server
  54. } // namespace fl
  55. } // namespace mindspore