1 /*
2   Copyright (c) DataStax, Inc.
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 #ifndef DATASTAX_INTERNAL_TOKEN_AWARE_POLICY_HPP
18 #define DATASTAX_INTERNAL_TOKEN_AWARE_POLICY_HPP
19 
20 #include "host.hpp"
21 #include "load_balancing.hpp"
22 #include "scoped_ptr.hpp"
23 #include "token_map.hpp"
24 
25 namespace datastax { namespace internal { namespace core {
26 
27 class TokenAwarePolicy : public ChainedLoadBalancingPolicy {
28 public:
TokenAwarePolicy(LoadBalancingPolicy * child_policy,bool shuffle_replicas)29   TokenAwarePolicy(LoadBalancingPolicy* child_policy, bool shuffle_replicas)
30       : ChainedLoadBalancingPolicy(child_policy)
31       , random_(NULL)
32       , index_(0)
33       , shuffle_replicas_(shuffle_replicas) {}
34 
~TokenAwarePolicy()35   virtual ~TokenAwarePolicy() {}
36 
37   virtual void init(const Host::Ptr& connected_host, const HostMap& hosts, Random* random,
38                     const String& local_dc);
39 
40   virtual QueryPlan* new_query_plan(const String& keyspace, RequestHandler* request_handler,
41                                     const TokenMap* token_map);
42 
new_instance()43   LoadBalancingPolicy* new_instance() {
44     return new TokenAwarePolicy(child_policy_->new_instance(), shuffle_replicas_);
45   }
46 
47 private:
48   class TokenAwareQueryPlan : public QueryPlan {
49   public:
TokenAwareQueryPlan(LoadBalancingPolicy * child_policy,QueryPlan * child_plan,const CopyOnWriteHostVec & replicas,size_t start_index)50     TokenAwareQueryPlan(LoadBalancingPolicy* child_policy, QueryPlan* child_plan,
51                         const CopyOnWriteHostVec& replicas, size_t start_index)
52         : child_policy_(child_policy)
53         , child_plan_(child_plan)
54         , replicas_(replicas)
55         , index_(start_index)
56         , remaining_(replicas->size()) {}
57 
58     Host::Ptr compute_next();
59 
60   private:
61     LoadBalancingPolicy* child_policy_;
62     ScopedPtr<QueryPlan> child_plan_;
63     CopyOnWriteHostVec replicas_;
64     size_t index_;
65     size_t remaining_;
66   };
67 
68   Random* random_;
69   size_t index_;
70   bool shuffle_replicas_;
71 
72 private:
73   DISALLOW_COPY_AND_ASSIGN(TokenAwarePolicy);
74 };
75 }}} // namespace datastax::internal::core
76 
77 #endif
78