PageRenderTime 83ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/src/java/org/apache/cassandra/dht/OrderPreservingPartitioner.java

https://github.com/beobal/cassandra
Java | 259 lines | 190 code | 36 blank | 33 comment | 11 complexity | 72adf77d0b5f82a311a5af7297f21eff MD5 | raw file
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. package org.apache.cassandra.dht;
  19. import java.math.BigInteger;
  20. import java.nio.ByteBuffer;
  21. import java.nio.charset.CharacterCodingException;
  22. import java.util.*;
  23. import java.util.concurrent.ThreadLocalRandom;
  24. import org.apache.cassandra.db.DecoratedKey;
  25. import org.apache.cassandra.db.CachedHashDecoratedKey;
  26. import org.apache.cassandra.db.marshal.AbstractType;
  27. import org.apache.cassandra.db.marshal.UTF8Type;
  28. import org.apache.cassandra.exceptions.ConfigurationException;
  29. import org.apache.cassandra.gms.VersionedValue;
  30. import org.apache.cassandra.schema.Schema;
  31. import org.apache.cassandra.schema.TableMetadata;
  32. import org.apache.cassandra.service.StorageService;
  33. import org.apache.cassandra.utils.ByteBufferUtil;
  34. import org.apache.cassandra.utils.FBUtilities;
  35. import org.apache.cassandra.utils.ObjectSizes;
  36. import org.apache.cassandra.utils.Pair;
  37. public class OrderPreservingPartitioner implements IPartitioner
  38. {
  39. private static final String rndchars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  40. public static final StringToken MINIMUM = new StringToken("");
  41. public static final BigInteger CHAR_MASK = new BigInteger("65535");
  42. private static final long EMPTY_SIZE = ObjectSizes.measure(MINIMUM);
  43. public static final OrderPreservingPartitioner instance = new OrderPreservingPartitioner();
  44. public DecoratedKey decorateKey(ByteBuffer key)
  45. {
  46. return new CachedHashDecoratedKey(getToken(key), key);
  47. }
  48. public StringToken midpoint(Token ltoken, Token rtoken)
  49. {
  50. int sigchars = Math.max(((StringToken)ltoken).token.length(), ((StringToken)rtoken).token.length());
  51. BigInteger left = bigForString(((StringToken)ltoken).token, sigchars);
  52. BigInteger right = bigForString(((StringToken)rtoken).token, sigchars);
  53. Pair<BigInteger,Boolean> midpair = FBUtilities.midpoint(left, right, 16*sigchars);
  54. return new StringToken(stringForBig(midpair.left, sigchars, midpair.right));
  55. }
  56. public Token split(Token left, Token right, double ratioToLeft)
  57. {
  58. throw new UnsupportedOperationException();
  59. }
  60. /**
  61. * Copies the characters of the given string into a BigInteger.
  62. *
  63. * TODO: Does not acknowledge any codepoints above 0xFFFF... problem?
  64. */
  65. private static BigInteger bigForString(String str, int sigchars)
  66. {
  67. assert str.length() <= sigchars;
  68. BigInteger big = BigInteger.ZERO;
  69. for (int i = 0; i < str.length(); i++)
  70. {
  71. int charpos = 16 * (sigchars - (i + 1));
  72. BigInteger charbig = BigInteger.valueOf(str.charAt(i) & 0xFFFF);
  73. big = big.or(charbig.shiftLeft(charpos));
  74. }
  75. return big;
  76. }
  77. /**
  78. * Convert a (positive) BigInteger into a String.
  79. * If remainder is true, an additional char with the high order bit enabled
  80. * will be added to the end of the String.
  81. */
  82. private String stringForBig(BigInteger big, int sigchars, boolean remainder)
  83. {
  84. char[] chars = new char[sigchars + (remainder ? 1 : 0)];
  85. if (remainder)
  86. // remaining bit is the most significant in the last char
  87. chars[sigchars] |= 0x8000;
  88. for (int i = 0; i < sigchars; i++)
  89. {
  90. int maskpos = 16 * (sigchars - (i + 1));
  91. // apply bitmask and get char value
  92. chars[i] = (char)(big.and(CHAR_MASK.shiftLeft(maskpos)).shiftRight(maskpos).intValue() & 0xFFFF);
  93. }
  94. return new String(chars);
  95. }
  96. public StringToken getMinimumToken()
  97. {
  98. return MINIMUM;
  99. }
  100. public StringToken getRandomToken()
  101. {
  102. return getRandomToken(ThreadLocalRandom.current());
  103. }
  104. public StringToken getRandomToken(Random random)
  105. {
  106. StringBuilder buffer = new StringBuilder();
  107. for (int j = 0; j < 16; j++)
  108. buffer.append(rndchars.charAt(random.nextInt(rndchars.length())));
  109. return new StringToken(buffer.toString());
  110. }
  111. private final Token.TokenFactory tokenFactory = new Token.TokenFactory()
  112. {
  113. public ByteBuffer toByteArray(Token token)
  114. {
  115. StringToken stringToken = (StringToken) token;
  116. return ByteBufferUtil.bytes(stringToken.token);
  117. }
  118. public Token fromByteArray(ByteBuffer bytes)
  119. {
  120. try
  121. {
  122. return new StringToken(ByteBufferUtil.string(bytes));
  123. }
  124. catch (CharacterCodingException e)
  125. {
  126. throw new RuntimeException(e);
  127. }
  128. }
  129. public String toString(Token token)
  130. {
  131. StringToken stringToken = (StringToken) token;
  132. return stringToken.token;
  133. }
  134. public void validate(String token) throws ConfigurationException
  135. {
  136. if (token.contains(VersionedValue.DELIMITER_STR))
  137. throw new ConfigurationException("Tokens may not contain the character " + VersionedValue.DELIMITER_STR);
  138. }
  139. public Token fromString(String string)
  140. {
  141. return new StringToken(string);
  142. }
  143. };
  144. public Token.TokenFactory getTokenFactory()
  145. {
  146. return tokenFactory;
  147. }
  148. public boolean preservesOrder()
  149. {
  150. return true;
  151. }
  152. public static class StringToken extends ComparableObjectToken<String>
  153. {
  154. static final long serialVersionUID = 5464084395277974963L;
  155. public StringToken(String token)
  156. {
  157. super(token);
  158. }
  159. @Override
  160. public IPartitioner getPartitioner()
  161. {
  162. return instance;
  163. }
  164. @Override
  165. public long getHeapSize()
  166. {
  167. return EMPTY_SIZE + ObjectSizes.sizeOf(token);
  168. }
  169. }
  170. public StringToken getToken(ByteBuffer key)
  171. {
  172. String skey;
  173. try
  174. {
  175. skey = ByteBufferUtil.string(key);
  176. }
  177. catch (CharacterCodingException e)
  178. {
  179. skey = ByteBufferUtil.bytesToHex(key);
  180. }
  181. return new StringToken(skey);
  182. }
  183. public Map<Token, Float> describeOwnership(List<Token> sortedTokens)
  184. {
  185. // allTokens will contain the count and be returned, sorted_ranges is shorthand for token<->token math.
  186. Map<Token, Float> allTokens = new HashMap<Token, Float>();
  187. List<Range<Token>> sortedRanges = new ArrayList<Range<Token>>(sortedTokens.size());
  188. // this initializes the counts to 0 and calcs the ranges in order.
  189. Token lastToken = sortedTokens.get(sortedTokens.size() - 1);
  190. for (Token node : sortedTokens)
  191. {
  192. allTokens.put(node, new Float(0.0));
  193. sortedRanges.add(new Range<Token>(lastToken, node));
  194. lastToken = node;
  195. }
  196. for (String ks : Schema.instance.getKeyspaces())
  197. {
  198. for (TableMetadata cfmd : Schema.instance.getTablesAndViews(ks))
  199. {
  200. for (Range<Token> r : sortedRanges)
  201. {
  202. // Looping over every KS:CF:Range, get the splits size and add it to the count
  203. allTokens.put(r.right, allTokens.get(r.right) + StorageService.instance.getSplits(ks, cfmd.name, r, cfmd.params.minIndexInterval).size());
  204. }
  205. }
  206. }
  207. // Sum every count up and divide count/total for the fractional ownership.
  208. Float total = new Float(0.0);
  209. for (Float f : allTokens.values())
  210. total += f;
  211. for (Map.Entry<Token, Float> row : allTokens.entrySet())
  212. allTokens.put(row.getKey(), row.getValue() / total);
  213. return allTokens;
  214. }
  215. public AbstractType<?> getTokenValidator()
  216. {
  217. return UTF8Type.instance;
  218. }
  219. public AbstractType<?> partitionOrdering()
  220. {
  221. return UTF8Type.instance;
  222. }
  223. }