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 17 #include "fl/server/consistent_hash_ring.h" 18 19 namespace mindspore { 20 namespace fl { 21 namespace server { Insert(uint32_t rank)22bool ConsistentHashRing::Insert(uint32_t rank) { 23 for (uint32_t i = 0; i < virtual_node_num_; i++) { 24 std::string physical_node_hash_key = std::to_string(rank) + "#" + std::to_string(i); 25 size_t hash_value = std::hash<std::string>()(physical_node_hash_key); 26 MS_LOG(DEBUG) << "Insert virtual node " << physical_node_hash_key << " for node " << rank << ", hash value is " 27 << hash_value; 28 if (ring_.count(hash_value) != 0) { 29 MS_LOG(INFO) << "Virtual node " << physical_node_hash_key << " is already mapped to the ring."; 30 continue; 31 } 32 ring_[hash_value] = rank; 33 } 34 return true; 35 } 36 Erase(uint32_t rank)37bool ConsistentHashRing::Erase(uint32_t rank) { 38 for (auto iterator = ring_.begin(); iterator != ring_.end();) { 39 if (iterator->second == rank) { 40 (void)ring_.erase(iterator++); 41 } else { 42 ++iterator; 43 } 44 } 45 return true; 46 } 47 Find(const std::string & key)48uint32_t ConsistentHashRing::Find(const std::string &key) { 49 size_t hash_value = std::hash<std::string>()(key); 50 auto iterator = ring_.lower_bound(hash_value); 51 if (iterator == ring_.end()) { 52 // If the virtual node is not found clockwise, the key will be mapped to the first virtual node on the ring. 53 iterator = ring_.begin(); 54 } 55 return iterator->second; 56 } 57 } // namespace server 58 } // namespace fl 59 } // namespace mindspore 60