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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 "ps/server/consistent_hash_ring.h"
  17. namespace mindspore {
  18. namespace ps {
  19. namespace server {
  20. bool ConsistentHashRing::Insert(uint32_t rank) {
  21. std::string physical_node_hash_key = std::to_string(rank);
  22. for (uint32_t i = 0; i < virtual_node_num_; i++) {
  23. physical_node_hash_key += "#" + std::to_string(i);
  24. MS_LOG(DEBUG) << "Insert virtual node " << physical_node_hash_key << " for node " << rank;
  25. size_t hash_value = std::hash<std::string>()(physical_node_hash_key);
  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. ring_.erase(iterator++);
  38. }
  39. }
  40. return true;
  41. }
  42. uint32_t ConsistentHashRing::Find(const std::string &key) {
  43. size_t hash_value = std::hash<std::string>()(key);
  44. auto iterator = ring_.lower_bound(hash_value);
  45. if (iterator == ring_.end()) {
  46. // If the virtual node is not found clockwise, the key will be mapped to the first virtual node on the ring.
  47. iterator = ring_.begin();
  48. }
  49. return iterator->second;
  50. }
  51. } // namespace server
  52. } // namespace ps
  53. } // namespace mindspore