Skip to content
Browse files

PASC Paxos release

  • Loading branch information...
0 parents commit c5fb8971873ce7fea9b667c4a669355b17bc7ee4 @dgomezferro dgomezferro committed
Showing with 6,722 additions and 0 deletions.
  1. +202 −0 LICENSE.txt
  2. +9 −0 NOTICE.txt
  3. +10 −0 README
  4. +43 −0 conf/log4j.properties
  5. +138 −0 pom.xml
  6. +178 −0 src/main/java/com/yahoo/paxos/client/Barrier.java
  7. +26 −0 src/main/java/com/yahoo/paxos/client/ClientInterface.java
  8. +106 −0 src/main/java/com/yahoo/paxos/client/ClientState.java
  9. +38 −0 src/main/java/com/yahoo/paxos/client/Connected.java
  10. +205 −0 src/main/java/com/yahoo/paxos/client/PaxosClient.java
  11. +276 −0 src/main/java/com/yahoo/paxos/client/PaxosClientHandler.java
  12. +22 −0 src/main/java/com/yahoo/paxos/client/PaxosInterface.java
  13. +41 −0 src/main/java/com/yahoo/paxos/client/SimpleClient.java
  14. +55 −0 src/main/java/com/yahoo/paxos/client/handlers/HelloHandler.java
  15. +74 −0 src/main/java/com/yahoo/paxos/client/handlers/ReplyHandler.java
  16. +55 −0 src/main/java/com/yahoo/paxos/client/handlers/SubmitHandler.java
  17. +51 −0 src/main/java/com/yahoo/paxos/client/handlers/TimeoutHandler.java
  18. +68 −0 src/main/java/com/yahoo/paxos/client/messages/Received.java
  19. +68 −0 src/main/java/com/yahoo/paxos/client/messages/Submit.java
  20. +50 −0 src/main/java/com/yahoo/paxos/client/messages/Timeout.java
  21. +100 −0 src/main/java/com/yahoo/paxos/handlers/DigestHandler.java
  22. +50 −0 src/main/java/com/yahoo/paxos/handlers/PaxosHandler.java
  23. +129 −0 src/main/java/com/yahoo/paxos/handlers/acceptor/AcceptorAccept.java
  24. +41 −0 src/main/java/com/yahoo/paxos/handlers/acceptor/AcceptorPrepare.java
  25. +120 −0 src/main/java/com/yahoo/paxos/handlers/learner/Learner.java
  26. +74 −0 src/main/java/com/yahoo/paxos/handlers/learner/LearnerPreReply.java
  27. +41 −0 src/main/java/com/yahoo/paxos/handlers/proposer/ProposerPrepared.java
  28. +218 −0 src/main/java/com/yahoo/paxos/handlers/proposer/ProposerRequest.java
  29. +165 −0 src/main/java/com/yahoo/paxos/messages/Accept.java
  30. +102 −0 src/main/java/com/yahoo/paxos/messages/Accepted.java
  31. +102 −0 src/main/java/com/yahoo/paxos/messages/Digest.java
  32. +156 −0 src/main/java/com/yahoo/paxos/messages/Execute.java
  33. +57 −0 src/main/java/com/yahoo/paxos/messages/Hello.java
  34. +45 −0 src/main/java/com/yahoo/paxos/messages/InlineRequest.java
  35. +68 −0 src/main/java/com/yahoo/paxos/messages/MessageType.java
  36. +26 −0 src/main/java/com/yahoo/paxos/messages/PaxosDescriptor.java
  37. +109 −0 src/main/java/com/yahoo/paxos/messages/PaxosMessage.java
  38. +127 −0 src/main/java/com/yahoo/paxos/messages/PreReply.java
  39. +67 −0 src/main/java/com/yahoo/paxos/messages/Prepare.java
  40. +27 −0 src/main/java/com/yahoo/paxos/messages/Prepared.java
  41. +137 −0 src/main/java/com/yahoo/paxos/messages/Reply.java
  42. +85 −0 src/main/java/com/yahoo/paxos/messages/Request.java
  43. +51 −0 src/main/java/com/yahoo/paxos/messages/serialization/BufferPool.java
  44. +38 −0 src/main/java/com/yahoo/paxos/messages/serialization/CRC32Pool.java
  45. +189 −0 src/main/java/com/yahoo/paxos/messages/serialization/ManualDecoder.java
  46. +213 −0 src/main/java/com/yahoo/paxos/messages/serialization/ManualEncoder.java
  47. +351 −0 src/main/java/com/yahoo/paxos/messages/serialization/PureJavaCrc32.java
  48. +34 −0 src/main/java/com/yahoo/paxos/server/ChannelDownstreamEventRunnable.java
  49. +45 −0 src/main/java/com/yahoo/paxos/server/DownstreamExecutionHandler.java
  50. +151 −0 src/main/java/com/yahoo/paxos/server/PaxosServer.java
  51. +100 −0 src/main/java/com/yahoo/paxos/server/PipelineFactory.java
  52. +34 −0 src/main/java/com/yahoo/paxos/server/ServerConnection.java
  53. +155 −0 src/main/java/com/yahoo/paxos/server/ServerHandler.java
  54. +209 −0 src/main/java/com/yahoo/paxos/server/tcp/TcpServer.java
  55. +157 −0 src/main/java/com/yahoo/paxos/server/udp/UdpServer.java
  56. +21 −0 src/main/java/com/yahoo/paxos/state/ApplicationState.java
  57. +84 −0 src/main/java/com/yahoo/paxos/state/ClientTimestamp.java
  58. +111 −0 src/main/java/com/yahoo/paxos/state/DigestStore.java
  59. +109 −0 src/main/java/com/yahoo/paxos/state/IidAcceptorsCounts.java
  60. +75 −0 src/main/java/com/yahoo/paxos/state/IidRequest.java
  61. +84 −0 src/main/java/com/yahoo/paxos/state/IndexIid.java
  62. +114 −0 src/main/java/com/yahoo/paxos/state/InstanceRecord.java
  63. +426 −0 src/main/java/com/yahoo/paxos/state/PaxosState.java
  64. +57 −0 src/main/java/com/yahoo/paxos/state/TimestampReply.java
  65. +31 −0 src/main/java/com/yahoo/paxos/statemachine/EmptyStateMachine.java
  66. +22 −0 src/main/java/com/yahoo/paxos/statemachine/StateMachine.java
  67. +25 −0 src/main/java/com/yahoo/paxos/util/Util.java
  68. +75 −0 src/test/java/com/yahoo/paxos/PaxosEnsemble.java
202 LICENSE.txt
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
9 NOTICE.txt
@@ -0,0 +1,9 @@
+=======================================================================
+NOTICE file for use with, and corresponding to Section 4 of,
+the Apache License, Version 2.0,
+in this case for the CrTSO project. ==
+=========================================================================
+
+ This product includes software developed by
+ Yahoo! Inc. (www.yahoo.com)
+ Copyright (c) 2010 Yahoo! Inc. All rights reserved.
10 README
@@ -0,0 +1,10 @@
+* Dependencies
+ - Pasc
+ - Netty
+ - ZooKeeper
+
+* Compilation
+
+ Paxos uses maven for its buildsystem. Compile with
+
+ $ mvn install
43 conf/log4j.properties
@@ -0,0 +1,43 @@
+########################################################################
+#
+# Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License. See accompanying LICENSE file.
+#
+########################################################################
+
+#log4j.rootCategory=TRACE, R, O
+log4j.rootCategory=WARN, R, O
+
+# Stdout
+log4j.appender.O=org.apache.log4j.ConsoleAppender
+#log4j.appender.O.Threshold=WARN
+
+# File
+log4j.appender.R=org.apache.log4j.RollingFileAppender
+log4j.appender.R.File=logs/log4j.log
+
+# Control the maximum log file size
+log4j.appender.R.MaxFileSize=100MB
+
+# Clear log file each time
+log4j.appender.R.Append=false
+
+# Archive log files (one backup file here)
+log4j.appender.R.MaxBackupIndex=5
+
+log4j.appender.R.layout=org.apache.log4j.PatternLayout
+log4j.appender.O.layout=org.apache.log4j.PatternLayout
+
+log4j.appender.R.layout.ConversionPattern=[%d{ISO8601}]%5p%6.6r[%t]%x - %C.%M(%F:%L) - %m%n
+log4j.appender.O.layout.ConversionPattern=[%d{ISO8601}]%5p%6.6r[%t]%x - %C.%M(%F:%L) - %m%n
138 pom.xml
@@ -0,0 +1,138 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>Paxos</groupId>
+ <artifactId>Paxos</artifactId>
+ <version>0.0.1-SNAPSHOT</version>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-dependency-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>copy-dependencies</id>
+ <phase>package</phase>
+ <goals>
+ <goal>copy-dependencies</goal>
+ </goals>
+ <configuration>
+ <outputDirectory>${project.build.directory}</outputDirectory>
+ <overWriteReleases>false</overWriteReleases>
+ <overWriteSnapshots>true</overWriteSnapshots>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+ <dependencies>
+ <dependency>
+ <groupId>Pasc</groupId>
+ <artifactId>Pasc</artifactId>
+ <version>0.0.1-SNAPSHOT</version>
+ <type>jar</type>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>commons-logging</groupId>
+ <artifactId>commons-logging</artifactId>
+ <version>1.1.1</version>
+ <type>jar</type>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>it.unimi.dsi</groupId>
+ <artifactId>fastutil</artifactId>
+ <version>6.3</version>
+ <type>jar</type>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>commons-cli</groupId>
+ <artifactId>commons-cli</artifactId>
+ <version>1.2</version>
+ <type>jar</type>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.zookeeper</groupId>
+ <artifactId>zookeeper</artifactId>
+ <version>3.3.3</version>
+ <type>jar</type>
+ <scope>compile</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>com.sun.jmx</groupId>
+ <artifactId>jmxri</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>com.sun.jdmk</groupId>
+ <artifactId>jmxtools</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>javax.jms</groupId>
+ <artifactId>jms</artifactId>
+ </exclusion>
+ </exclusions>
+
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.netty</groupId>
+ <artifactId>netty</artifactId>
+ <version>3.2.5.Final</version>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>log4j</groupId>
+ <artifactId>log4j</artifactId>
+ <version>1.2.15</version>
+ <type>jar</type>
+ <scope>runtime</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>com.sun.jmx</groupId>
+ <artifactId>jmxri</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>com.sun.jdmk</groupId>
+ <artifactId>jmxtools</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>javax.jms</groupId>
+ <artifactId>jms</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-log4j12</artifactId>
+ <version>1.6.2</version>
+ <type>jar</type>
+ <scope>runtime</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ <version>1.6.2</version>
+ <type>jar</type>
+ <scope>compile</scope>
+ </dependency>
+ </dependencies>
+</project>
178 src/main/java/com/yahoo/paxos/client/Barrier.java
@@ -0,0 +1,178 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License. See accompanying LICENSE file.
+ */
+
+package com.yahoo.paxos.client;
+
+import java.io.IOException;
+import java.util.Random;
+
+import org.apache.zookeeper.CreateMode;
+import org.apache.zookeeper.KeeperException;
+import org.apache.zookeeper.KeeperException.Code;
+import org.apache.zookeeper.Watcher;
+import org.apache.zookeeper.ZooDefs.Ids;
+import org.apache.zookeeper.ZooKeeper;
+import org.apache.zookeeper.data.Stat;
+
+public class Barrier implements Watcher {
+ private int size;
+ private String name;
+ private ZooKeeper zk;
+ private Object mutex;
+ private String root;
+
+ /**
+ * Barrier constructor
+ *
+ * @param address
+ * @param root
+ * @param size
+ * @throws IOException
+ * @throws KeeperException
+ */
+ Barrier(String address, String root, String name, int size) throws KeeperException, IOException {
+ zk = new ZooKeeper(address, 5000, this);
+ this.mutex = new Object();
+ this.root = root;
+ this.size = size;
+ this.name = name;
+
+ try {
+ zk.create(root, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ } catch (KeeperException e) {
+ if (e.code().equals(Code.NODEEXISTS)) {
+ //ignore
+ } else {
+ System.out.println("Keeper exception when instantiating barrier: " + e.toString());
+ }
+ } catch (InterruptedException e) {
+ System.out.println("Interrupted exception");
+ }
+ }
+
+ /**
+ * Join barrier
+ *
+ * @return
+ * @throws KeeperException
+ * @throws InterruptedException
+ */
+
+ boolean enter() throws KeeperException, InterruptedException {
+ zk.create(root + "/" + name, null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
+ if (zk.getChildren(root, false).size() == size) {
+ try {
+ zk.create(root + "/start", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ } catch (KeeperException e) {
+ if (e.code().equals(Code.NODEEXISTS)) {
+ return true;
+ } else throw e;
+ }
+ return true;
+ }
+ while (true) {
+ synchronized (mutex) {
+ Stat stat = zk.exists(root + "/start", true);
+ if (stat != null) {
+ return true;
+ }
+ mutex.wait();
+ }
+ }
+ }
+
+ /**
+ * Wait until all reach barrier
+ *
+ * @return
+ * @throws KeeperException
+ * @throws InterruptedException
+ */
+ boolean leave() throws KeeperException, InterruptedException {
+ zk.delete(root + "/" + name, -1);
+ while (true) {
+ synchronized (mutex) {
+ int children = zk.getChildren(root, true).size();
+ if (children == 1) {
+ try {
+ zk.delete(root + "/start", -1);
+ } catch (KeeperException e) {
+ if (e.code().equals(Code.NONODE)) {
+ return true;
+ } else throw e;
+ }
+ } else if (children == 0) {
+ return true;
+ } else {
+ mutex.wait();
+ }
+ }
+ }
+ }
+
+ @Override
+ public void process(org.apache.zookeeper.WatchedEvent arg0) {
+ synchronized (mutex) {
+ mutex.notify();
+ }
+ }
+
+ void close() throws InterruptedException {
+ zk.close();
+ }
+}
+
+class Worker implements Runnable {
+ private static Random rand = new Random();
+ private String name;
+ private int size;
+
+ public Worker(String name, int size) {
+ this.name = name;
+ this.size = size;
+ }
+
+ @Override
+ public void run() {
+ try {
+ Thread.currentThread().setName("Worker " + name);
+ doWork();
+ } catch (KeeperException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (InterruptedException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+
+ private void doWork() throws KeeperException, IOException, InterruptedException {
+ Barrier b = new Barrier("localhost:3000", "/test", name, size);
+ Thread.sleep(rand.nextInt(10000));
+ b.enter();
+ System.out.println("Worker " + name + " starting work.");
+ Thread.sleep(rand.nextInt(11000));
+ b.leave();
+ System.out.println("Worker " + name + " finished work.");
+ }
+}
+
+enum State {
+ ENTERING, CLOSED, LEAVING
+}
26 src/main/java/com/yahoo/paxos/client/ClientInterface.java
@@ -0,0 +1,26 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License. See accompanying LICENSE file.
+ */
+
+package com.yahoo.paxos.client;
+
+public interface ClientInterface {
+
+ public void setInterface(PaxosInterface paxosInterface);
+
+ public void messageReceived(byte[] message);
+
+ public void connected();
+}
106 src/main/java/com/yahoo/paxos/client/ClientState.java
@@ -0,0 +1,106 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License. See accompanying LICENSE file.
+ */
+
+package com.yahoo.paxos.client;
+
+import java.util.BitSet;
+
+import com.yahoo.pasc.ProcessState;
+import com.yahoo.paxos.messages.Request;
+
+public class ClientState implements ProcessState {
+ int clientId;
+ int servers;
+ int quorum;
+ int connected;
+ int inlineThreshold;
+
+ long timestamp = 0;
+ Request pendingRequest;
+ BitSet acks = new BitSet();
+
+ public ClientState(int clientId, int servers, int quorum, int inlineThreshold) {
+ this.clientId = clientId;
+ this.servers = servers;
+ this.quorum = quorum;
+ this.inlineThreshold = inlineThreshold;
+ }
+
+ public int getClientId() {
+ return clientId;
+ }
+
+ public void setClientId(int clientId) {
+ this.clientId = clientId;
+ }
+
+ public int getServers() {
+ return servers;
+ }
+
+ public void setServers(int servers) {
+ this.servers = servers;
+ }
+
+ public int getQuorum() {
+ return quorum;
+ }
+
+ public void setQuorum(int quorum) {
+ this.quorum = quorum;
+ }
+
+ public int getConnected() {
+ return connected;
+ }
+
+ public void setConnected(int connected) {
+ this.connected = connected;
+ }
+
+ public long getTimestamp() {
+ return timestamp;
+ }
+
+ public void setTimestamp(long timestamp) {
+ this.timestamp = timestamp;
+ }
+
+ public Request getPendingRequest() {
+ return pendingRequest;
+ }
+
+ public void setPendingRequest(Request pendingRequest) {
+ this.pendingRequest = pendingRequest;
+ }
+
+ public BitSet getAcks() {
+ return acks;
+ }
+
+ public void setAcks(BitSet acks) {
+ this.acks = acks;
+ }
+
+ public int getInlineThreshold() {
+ return inlineThreshold;
+ }
+
+ public void setInlineThreshold(int inlineThreshold) {
+ this.inlineThreshold = inlineThreshold;
+ }
+
+}
38 src/main/java/com/yahoo/paxos/client/Connected.java
@@ -0,0 +1,38 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License. See accompanying LICENSE file.
+ */
+
+package com.yahoo.paxos.client;
+
+import com.yahoo.pasc.Message;
+import com.yahoo.pasc.MessageDescriptor;
+
+public class Connected extends Message {
+
+ public static class Descriptor implements MessageDescriptor {
+
+ }
+
+ @Override
+ protected boolean verify() {
+ return true;
+ }
+
+ @Override
+ public void storeReplica(Message m) {
+
+ }
+
+}
205 src/main/java/com/yahoo/paxos/client/PaxosClient.java
@@ -0,0 +1,205 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License. See accompanying LICENSE file.
+ */
+
+package com.yahoo.paxos.client;
+
+import java.net.InetSocketAddress;
+import java.util.Random;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.CommandLineParser;
+import org.apache.commons.cli.HelpFormatter;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.PosixParser;
+import org.jboss.netty.bootstrap.ClientBootstrap;
+import org.jboss.netty.bootstrap.ConnectionlessBootstrap;
+import org.jboss.netty.channel.ChannelPipeline;
+import org.jboss.netty.channel.ChannelPipelineFactory;
+import org.jboss.netty.channel.Channels;
+import org.jboss.netty.channel.socket.DatagramChannel;
+import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
+import org.jboss.netty.channel.socket.nio.NioDatagramChannelFactory;
+import org.jboss.netty.handler.execution.ExecutionHandler;
+import org.jboss.netty.handler.execution.OrderedMemoryAwareThreadPoolExecutor;
+
+import com.yahoo.pasc.PascRuntime;
+import com.yahoo.paxos.client.handlers.HelloHandler;
+import com.yahoo.paxos.client.handlers.ReplyHandler;
+import com.yahoo.paxos.client.handlers.SubmitHandler;
+import com.yahoo.paxos.client.handlers.TimeoutHandler;
+import com.yahoo.paxos.client.messages.Submit;
+import com.yahoo.paxos.client.messages.Timeout;
+import com.yahoo.paxos.messages.Hello;
+import com.yahoo.paxos.messages.Reply;
+import com.yahoo.paxos.messages.serialization.ManualDecoder;
+import com.yahoo.paxos.messages.serialization.ManualEncoder;
+
+public class PaxosClient {
+ public static void main(String[] args) throws Exception {
+
+ CommandLineParser parser = new PosixParser();
+ Options options;
+
+ {
+ Option id = new Option("i", true, "client id");
+ Option clients = new Option("c", true, "number of clients");
+ Option host = new Option("l", true, "leader (hostname:port)");
+ Option servers = new Option("s", true, "number of servers");
+ Option quorum = new Option("q", true, "necesarry quorum at the client");
+ Option port = new Option("p", true, "port used by client");
+ Option buffer = new Option("b", true, "number of concurrent clients");
+ Option timeout = new Option("t", true, "timeout in milliseconds");
+ Option udp = new Option("u", false, "use UDP");
+ Option zookeeper = new Option("z", true, "zookeeper connection string");
+ Option warmup = new Option("w", true, "warmup messagges");
+ Option measuring = new Option("m", true, "measuring time");
+ Option request = new Option("r", true, "request size");
+ Option frequency = new Option("f", true, "frequency of throughput info");
+ Option anm = new Option("a", false, "use protection");
+ Option inlineThresh = new Option("n", true, "threshold for sending requests iNline with accepts ");
+
+ options = new Options();
+ options.addOption(id).addOption(host).addOption(servers).addOption(quorum).addOption(port).addOption(warmup)
+ .addOption(buffer).addOption(timeout).addOption(udp).addOption(zookeeper).addOption(clients)
+ .addOption(measuring).addOption(request).addOption(frequency).addOption(anm).addOption(inlineThresh);
+ }
+
+ CommandLine line = null;
+ try {
+ line = parser.parse(options, args);
+
+ String host = line.hasOption('l') ? line.getOptionValue('l') : "localhost:20548,localhost:20748,localhost:20778";
+ int clientIds = line.hasOption('i') ? Integer.parseInt(line.getOptionValue('i')) : 0;
+ int servers = line.hasOption('s') ? Integer.parseInt(line.getOptionValue('s')) : 3;
+ int quorum = line.hasOption('q') ? Integer.parseInt(line.getOptionValue('q')) : 1;
+ int buffer = line.hasOption('b') ? Integer.parseInt(line.getOptionValue('b')) : 1;
+ int clientPort = line.hasOption('p') ? Integer.parseInt(line.getOptionValue('p')) : 9000;
+ int timeout = line.hasOption('t') ? Integer.parseInt(line.getOptionValue('t')) : 5000;
+ int clients = line.hasOption('c') ? Integer.parseInt(line.getOptionValue('c')) : 1;
+ int requestSize = line.hasOption('r') ? Integer.parseInt(line.getOptionValue('r')) : 0;
+ int inlineThreshold = line.hasOption('n') ? Integer.parseInt(line.getOptionValue('n')) : 10;
+ boolean protection = line.hasOption('a');
+ boolean udp = line.hasOption('u');
+ String zkConnection = line.getOptionValue('z');
+
+
+ int threads = Runtime.getRuntime().availableProcessors() * 2;
+ final ExecutionHandler executor = new ExecutionHandler(new OrderedMemoryAwareThreadPoolExecutor(threads, 1024 * 1024,
+ 1024 * 1024 * 1024, 30, TimeUnit.SECONDS, Executors.defaultThreadFactory()));
+ final ManualEncoder encoder = new ManualEncoder();
+
+ String [] serverHosts = host.split(",");
+
+ HelloHandler hello = new HelloHandler();
+ ReplyHandler reply = new ReplyHandler();
+ SubmitHandler submit = new SubmitHandler();
+ TimeoutHandler tout = new TimeoutHandler();
+
+ Random rnd = new Random();
+
+ for (int i = 0; i < buffer; ++ i) {
+ int clientId = clientIds++;
+ ClientState clientState = new ClientState(clientId, servers, quorum, inlineThreshold);
+ final PascRuntime<ClientState> runtime = new PascRuntime<ClientState>(protection);
+ runtime.setState(clientState);
+ runtime.addHandler(Hello.class, hello);
+ runtime.addHandler(Reply.class, reply);
+ runtime.addHandler(Submit.class, submit);
+ runtime.addHandler(Timeout.class, tout);
+
+ final PaxosClientHandler handler = new PaxosClientHandler(runtime, new SimpleClient(requestSize),
+ clientId, clients, timeout, zkConnection);
+
+ if (line.hasOption('w')) handler.setWarmup(Integer.parseInt(line.getOptionValue('w')));
+ if (line.hasOption('m')) handler.setMeasuringTime(Integer.parseInt(line.getOptionValue('m')));
+// if (line.hasOption('r')) handler.setRequestSize(Integer.parseInt(line.getOptionValue('r')));
+ if (line.hasOption('f')) handler.setPeriod(Integer.parseInt(line.getOptionValue('f')));
+
+ ChannelPipelineFactory channelPipelineFactory = new ChannelPipelineFactory() {
+ public ChannelPipeline getPipeline() throws Exception {
+ // return Channels.pipeline(new KryoEncoder(kryo), new KryoDecoder(kryo), executor, handler);
+ return Channels.pipeline(encoder, new ManualDecoder(), executor, handler);
+// return Channels.pipeline(new ObjectEncoder(), new ObjectDecoder(), executor, handler);
+ }
+ };
+
+ if (udp) {
+ startUdpClient(channelPipelineFactory, clientPort, serverHosts);
+ } else {
+ startTcpClient(channelPipelineFactory, clientPort, serverHosts);
+ }
+
+ Thread.sleep(rnd.nextInt(200));
+ }
+ } catch (Exception e) {
+ System.err.println("Unexpected exception " + e);
+ e.printStackTrace();
+
+ HelpFormatter formatter = new HelpFormatter();
+ formatter.printHelp("Paxos", options);
+
+ System.exit(-1);
+ }
+ }
+
+ private static void startUdpClient(ChannelPipelineFactory channelPipelineFactory, int clientPort, String[] hosts) {
+
+ // Configure the client.
+ ConnectionlessBootstrap bootstrap = new ConnectionlessBootstrap(new NioDatagramChannelFactory(
+ Executors.newCachedThreadPool()));
+
+ // Set up the pipeline factory.
+ bootstrap.setPipelineFactory(channelPipelineFactory);
+
+ // Start the connection attempt.
+ bootstrap.bind(new InetSocketAddress(clientPort));
+
+ for (String host : hosts) {
+ final String s[] = host.split(":");
+ final String hostname = s[0];
+ final int port = Integer.parseInt(s[1]);
+ System.out.println("Connecting to " + hostname + ":" + port);
+ DatagramChannel clientChannel = (DatagramChannel) bootstrap.bind(new InetSocketAddress(0));
+ clientChannel.connect(new InetSocketAddress(hostname, port)).awaitUninterruptibly();
+ }
+ }
+
+ private static void startTcpClient(ChannelPipelineFactory channelPipelineFactory, int clientPort, String [] hosts) {
+
+// startServer(channelPipelineFactory, clientPort);
+
+ // Configure the client.
+ ClientBootstrap bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(
+ Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
+
+ // Set up the pipeline factory.
+ bootstrap.setPipelineFactory(channelPipelineFactory);
+ bootstrap.setOption("tcpNoDelay", true);
+ bootstrap.setOption("keepAlive", true);
+
+ for (String host : hosts) {
+ final String s[] = host.split(":");
+ final String hostname = s[0];
+ final int port = Integer.parseInt(s[1]);
+ System.out.println("Connecting to " + hostname + ":" + port);
+ // Start the connection attempt.
+ bootstrap.connect(new InetSocketAddress(hostname, port));
+ }
+ }
+}
276 src/main/java/com/yahoo/paxos/client/PaxosClientHandler.java
@@ -0,0 +1,276 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License. See accompanying LICENSE file.
+ */
+
+package com.yahoo.paxos.client;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Timer;
+import java.util.TimerTask;
+
+import org.apache.zookeeper.KeeperException;
+import org.jboss.netty.channel.Channel;
+import org.jboss.netty.channel.ChannelHandlerContext;
+import org.jboss.netty.channel.ChannelStateEvent;
+import org.jboss.netty.channel.ExceptionEvent;
+import org.jboss.netty.channel.MessageEvent;
+import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
+import org.jboss.netty.channel.group.ChannelGroup;
+import org.jboss.netty.channel.group.DefaultChannelGroup;
+
+import com.yahoo.pasc.Message;
+import com.yahoo.pasc.PascRuntime;
+import com.yahoo.paxos.client.messages.Received;
+import com.yahoo.paxos.client.messages.Submit;
+import com.yahoo.paxos.client.messages.Timeout;
+import com.yahoo.paxos.messages.Hello;
+import com.yahoo.paxos.messages.InlineRequest;
+import com.yahoo.paxos.messages.Request;
+
+public class PaxosClientHandler extends SimpleChannelUpstreamHandler implements PaxosInterface {
+
+// private static final Logger LOG = LoggerFactory.getLogger(PaxosClientHandler.class);
+
+ private int clientId;
+ private int clients;
+ private int timeout;
+ private String zkConnection;
+ private int warmup = 20000;
+ private long measuringTime = 30000;
+ private ChannelGroup serverChannels = new DefaultChannelGroup("Servers");
+ private Channel leader = null;
+ private PascRuntime<ClientState> runtime;
+ private ClientInterface clientInterface;
+
+ /**
+ * Creates a client-side handler.
+ */
+ public PaxosClientHandler(PascRuntime<ClientState> runtime, ClientInterface clientInterface, int clientId, int clients,
+ int timeout, String zkConnection) {
+ this.clientId = clientId;
+ this.clients = clients;
+ this.timeout = timeout;
+ this.zkConnection = zkConnection;
+ this.runtime = runtime;
+ this.clientInterface = clientInterface;
+ this.clientInterface.setInterface(this);
+ Arrays.fill(payload, (byte)5);
+ }
+
+ private int period = 100;
+ private byte[] payload = new byte[1];
+ private int resubmits;
+ private Timer timer = new Timer("Resubmit Thread");
+ private TimerTask resubmit;
+ private boolean measureLatency = false;
+ private long totalTime = 0;
+ private long pendingSentTime = 0;
+ private int latencyReceived = 0;
+
+ class ResubmitTask extends TimerTask {
+ long timestamp;
+ public ResubmitTask(long timestamp) {
+ this.timestamp = timestamp;
+ }
+ @Override
+ public void run() {
+ resubmitRequest(timestamp);
+ }
+ }
+
+ @Override
+ public void submitNewRequest(byte[] request) {
+ if (resubmit != null) resubmit.cancel();
+ List<Message> messages = runtime.handleMessage(new Submit(request));
+ if (messages == null)
+ return;
+ for (Message m : messages) {
+// LOG.trace("Sending {}", m);
+ if (m instanceof InlineRequest) {
+ leader.write(m);
+ } else {
+ serverChannels.write(m);
+ }
+ pendingSentTime = System.nanoTime();
+// System.out.println("NOT RESUBMITTING");
+ resubmit = new ResubmitTask(((Request) m).getTimestamp());
+ timer.schedule(resubmit, timeout);
+ }
+ }
+
+ synchronized void resubmitRequest(long timestamp) {
+ List<Message> messages = runtime.handleMessage(new Timeout(timestamp));
+ if (messages == null)
+ return;
+ for (Message m : messages) {
+// LOG.trace("Sending {}", m);
+ resubmits++;
+ serverChannels.write(m);
+ resubmit = new ResubmitTask(timestamp);
+ timer.schedule(resubmit, timeout);
+ }
+ }
+
+ @Override
+ public synchronized void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
+ Hello hello = new Hello(clientId);
+ hello.storeReplica(hello);
+ e.getChannel().write(hello);
+ }
+
+ private long messagesReceived = 0;
+ private long lastReceived = 0;
+ private long lastTime = 0;
+
+ @Override
+ public synchronized void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
+ Object message = e.getMessage();
+ if (message instanceof Hello) {
+ Hello hello = (Hello) e.getMessage();
+ if (hello.getClientId() == 0) {
+ System.out.println("Setting leader to " + e.getChannel());
+ leader = e.getChannel();
+ }
+ serverChannels.add(e.getChannel());
+ }
+// LOG.trace("Received {}", message);
+ List<Message> messages = runtime.handleMessage((Message) message);
+ if (messages == null)
+ return;
+ for (Message m : messages) {
+// LOG.trace("Sending {}", m);
+ if (m instanceof Connected) {
+ lastTime = System.nanoTime();
+
+ if (zkConnection != null) {
+ new Thread(new ThroughputMonitor()).start();
+ }
+
+ clientInterface.connected();
+ } else if (m instanceof Received) {
+ ++messagesReceived;
+ if (messagesReceived % period == 0) {
+ long currentTime = System.nanoTime();
+ long elapsed = currentTime - lastTime;
+ System.out.println(String.format("%8d: %8.2f m/s Resubmits: %d", messagesReceived,
+ (messagesReceived - lastReceived) / ((double) elapsed / 1000000000), resubmits));
+ resubmits = 0;
+ lastTime = currentTime;
+ lastReceived = messagesReceived;
+ }
+ if (measureLatency) {
+ totalTime += System.nanoTime() - pendingSentTime;
+ latencyReceived++;
+ }
+
+ clientInterface.messageReceived(((Received)m).getReply());
+ }
+ }
+ }
+
+ @Override
+ public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
+ System.err.println("Unexpected exception from downstream: " + e.getCause());
+ e.getCause().printStackTrace();
+ e.getChannel().close();
+ }
+
+ public int getWarmup() {
+ return warmup;
+ }
+
+ public void setWarmup(int warmup) {
+ this.warmup = warmup;
+ }
+
+ public void setMeasuringTime(long measuringTime) {
+ this.measuringTime = measuringTime;
+ }
+
+ public long getMeasuringTime() {
+ return measuringTime;
+ }
+
+ public void setRequestSize(int size) {
+ payload = new byte[size];
+ Arrays.fill(payload, (byte) 6);
+ }
+
+ public int getPeriod() {
+ return period;
+ }
+
+ public void setPeriod(int period) {
+ this.period = period;
+ }
+
+ class ThroughputMonitor implements Runnable {
+ private Barrier barrier;
+ public ThroughputMonitor() {
+ try {
+ System.out.println("Size "+clients);
+ barrier = new Barrier(zkConnection, "/paxos", ""+clientId, clients);
+ } catch (KeeperException e) {
+// LOG.error("Couldnt create barrier", e);
+ System.out.println("Couldnt create barrier"); e.printStackTrace();
+ } catch (IOException e) {
+// LOG.error("Couldnt create barrier", e);
+ System.out.println("Couldnt create barrier"); e.printStackTrace();
+ }
+ }
+
+ @Override
+ public void run() {
+ try {
+ try {
+ Thread.sleep(warmup);
+ } catch (InterruptedException ignore) {
+ }
+// System.out.format("[%d] Entering barrier\n", clientId);
+ barrier.enter();
+// System.out.format("[%d] Entered barrier\n", clientId);
+ long startMessagges = messagesReceived;
+ long startTime = System.currentTimeMillis();
+ measureLatency = true;
+ try {
+ Thread.sleep(getMeasuringTime());
+ } catch (InterruptedException ignore) {
+ }
+// System.out.format("[%d] Leaving barrier\n", clientId);
+ barrier.leave();
+ System.out.println(String.format("Throughput: %8.8f m/s",
+ (messagesReceived - startMessagges) / ((double)(System.currentTimeMillis() - startTime)/1000)));
+ System.out.println(String.format("Latency: %4.4f ms",
+ (totalTime / (double) latencyReceived)/1000000));
+ System.out.flush();
+
+ barrier.close();
+
+ serverChannels.close();
+
+ Thread.sleep(2000);
+
+ System.exit(0);
+ } catch (KeeperException e) {
+ System.out.println("Couldnt measure throughput"); e.printStackTrace();
+ } catch (InterruptedException e) {
+ System.out.println("Couldnt measure throughput"); e.printStackTrace();
+ }
+ System.exit(-1);
+ }
+ }
+}
22 src/main/java/com/yahoo/paxos/client/PaxosInterface.java
@@ -0,0 +1,22 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License. See accompanying LICENSE file.
+ */
+
+package com.yahoo.paxos.client;
+
+public interface PaxosInterface {
+
+ public void submitNewRequest(byte [] request);
+}
41 src/main/java/com/yahoo/paxos/client/SimpleClient.java
@@ -0,0 +1,41 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License. See accompanying LICENSE file.
+ */
+
+package com.yahoo.paxos.client;
+
+public class SimpleClient implements ClientInterface {
+
+ private PaxosInterface paxos;
+ private byte[] payload;
+
+ public SimpleClient(int requestSize) {
+ payload = new byte[requestSize];
+ }
+
+ @Override
+ public void connected() {
+ paxos.submitNewRequest(payload);
+
+ }
+ @Override
+ public void messageReceived(byte[] message) {
+ paxos.submitNewRequest(payload);
+ }
+
+ public void setInterface(PaxosInterface paxosInterface) {
+ paxos = paxosInterface;
+ };
+}
55 src/main/java/com/yahoo/paxos/client/handlers/HelloHandler.java
@@ -0,0 +1,55 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License. See accompanying LICENSE file.
+ */
+
+package com.yahoo.paxos.client.handlers;
+
+import java.util.Arrays;
+import java.util.List;
+
+import com.yahoo.pasc.Message;
+import com.yahoo.pasc.MessageHandler;
+import com.yahoo.paxos.client.ClientState;
+import com.yahoo.paxos.client.Connected;
+import com.yahoo.paxos.messages.Hello;
+
+public class HelloHandler implements MessageHandler<Hello, ClientState, Connected.Descriptor> {
+
+ @Override
+ public boolean guardPredicate(Message receivedMessage) {
+ return receivedMessage instanceof Hello;
+ }
+
+ @Override
+ public List<Connected.Descriptor> processMessage(Hello hello, ClientState state) {
+ List<Connected.Descriptor> descriptors = null;
+ int connected = state.getConnected();
+ connected++;
+ state.setConnected(connected);
+ if (connected == state.getServers()) {
+ // Send the first message if connected to all servers
+ descriptors = Arrays.asList(new Connected.Descriptor());
+ }
+ return descriptors;
+ }
+
+ @Override
+ public List<Message> getSendMessages(ClientState state, List<Connected.Descriptor> descriptors) {
+ if (descriptors != null && descriptors.size() > 0) {
+ return Arrays.<Message> asList(new Connected());
+ }
+ return null;
+ }
+}
74 src/main/java/com/yahoo/paxos/client/handlers/ReplyHandler.java
@@ -0,0 +1,74 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License. See accompanying LICENSE file.
+ */
+
+package com.yahoo.paxos.client.handlers;
+
+import java.util.Arrays;
+import java.util.BitSet;
+import java.util.List;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.yahoo.pasc.Message;
+import com.yahoo.pasc.MessageHandler;
+import com.yahoo.paxos.client.ClientState;
+import com.yahoo.paxos.client.messages.Received;
+import com.yahoo.paxos.messages.Reply;
+
+public class ReplyHandler implements MessageHandler<Reply, ClientState, Received.Descriptor> {
+
+ @SuppressWarnings("unused")
+ private static final Logger LOG = LoggerFactory.getLogger(ReplyHandler.class);
+
+ @Override
+ public boolean guardPredicate(Message receivedMessage) {
+ return receivedMessage instanceof Reply;
+ }
+
+ @Override
+ public List<Received.Descriptor> processMessage(Reply reply, ClientState state) {
+ List<Received.Descriptor> descriptors = null;
+ if (matches(reply, state)) {
+// LOG.debug("Reply {} matches with state", reply, state.getPendingRequest());
+ BitSet acks = state.getAcks();
+ acks.set(reply.getServerId());
+ if (acks.cardinality() >= state.getQuorum()) {
+// LOG.debug("Reached quorum {}",state.getQuorum());
+ descriptors = Arrays.asList(new Received.Descriptor(reply.getValue()));
+ } else {
+// LOG.debug("Still no quorum {} (we are at {})", state.getQuorum(), acks.cardinality());
+ }
+ }
+ return descriptors;
+ }
+
+ @Override
+ public List<Message> getSendMessages(ClientState state, List<Received.Descriptor> descriptors) {
+ if (descriptors != null && descriptors.size() > 0) {
+ return Arrays.<Message> asList(new Received(descriptors.get(0).getValue()));
+ }
+ return null;
+ }
+
+ private boolean matches(Reply reply, ClientState state) {
+ if (reply.getClientId() != state.getClientId())
+ return false;
+ if (reply.getTimestamp() != state.getPendingRequest().getTimestamp())
+ return false;
+ return true;
+ }
+}
55 src/main/java/com/yahoo/paxos/client/handlers/SubmitHandler.java
@@ -0,0 +1,55 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License. See accompanying LICENSE file.
+ */
+
+package com.yahoo.paxos.client.handlers;
+
+import java.util.Arrays;
+import java.util.List;
+
+import com.yahoo.pasc.Message;
+import com.yahoo.pasc.MessageHandler;
+import com.yahoo.paxos.client.ClientState;
+import com.yahoo.paxos.client.messages.Submit;
+import com.yahoo.paxos.messages.InlineRequest;
+import com.yahoo.paxos.messages.Request;
+
+public class SubmitHandler implements MessageHandler<Submit, ClientState, Request> {
+
+ @Override
+ public boolean guardPredicate(Message receivedMessage) {
+ return receivedMessage instanceof Submit;
+ }
+
+ @Override
+ public List<Request> processMessage(Submit submit, ClientState state) {
+ long timestamp = state.getTimestamp();
+ timestamp++;
+ Request request;
+ if (submit.getRequest().length > state.getInlineThreshold()) {
+ request = new Request(state.getClientId(), timestamp, submit.getRequest());
+ } else {
+ request = new InlineRequest(state.getClientId(), timestamp, submit.getRequest());
+ }
+ state.setPendingRequest(request);
+ state.setTimestamp(timestamp);
+ return Arrays.asList(request);
+ }
+
+ @Override
+ public List<Message> getSendMessages(ClientState state, List<Request> messages) {
+ return Arrays.<Message>asList(messages.get(0));
+ }
+}
51 src/main/java/com/yahoo/paxos/client/handlers/TimeoutHandler.java
@@ -0,0 +1,51 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License. See accompanying LICENSE file.
+ */
+
+package com.yahoo.paxos.client.handlers;
+
+import java.util.Arrays;
+import java.util.List;
+
+import com.yahoo.pasc.Message;
+import com.yahoo.pasc.MessageHandler;
+import com.yahoo.paxos.client.ClientState;
+import com.yahoo.paxos.client.messages.Timeout;
+import com.yahoo.paxos.messages.Request;
+
+public class TimeoutHandler implements MessageHandler<Timeout, ClientState, Request> {
+
+ @Override
+ public boolean guardPredicate(Message receivedMessage) {
+ return receivedMessage instanceof Timeout;
+ }
+
+ @Override
+ public List<Request> processMessage(Timeout timeout, ClientState state) {
+ if (timeout.getTimestamp() == state.getTimestamp()) {
+ Request pendingRequest = state.getPendingRequest();
+ return Arrays.asList(new Request(pendingRequest.getClientId(), pendingRequest.getTimestamp(), pendingRequest.getRequest()));
+ }
+ return null;
+ }
+
+ @Override
+ public List<Message> getSendMessages(ClientState state, List<Request> messages) {
+ if (messages != null && messages.size() > 0) {
+ return Arrays.<Message>asList(messages.get(0));
+ }
+ return null;
+ }
+}
68 src/main/java/com/yahoo/paxos/client/messages/Received.java
@@ -0,0 +1,68 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License. See accompanying LICENSE file.
+ */
+
+package com.yahoo.paxos.client.messages;
+
+import com.yahoo.pasc.Message;
+import com.yahoo.pasc.MessageDescriptor;
+
+public class Received extends Message {
+
+ public static class Descriptor implements MessageDescriptor {
+
+ private byte[] value;
+
+ public Descriptor(byte[] value) {
+ this.value = value;
+ }
+
+ public byte[] getValue() {
+ return value;
+ }
+
+ public void setValue(byte[] value) {
+ this.value = value;
+ }
+ }
+
+ byte[] reply;
+
+ public Received() {
+ }
+
+ public Received(byte[] reply) {
+ this.reply = reply;
+ }
+
+ public byte[] getReply() {
+ return reply;
+ }
+
+ public void setReply(byte[] reply) {
+ this.reply = reply;
+ }
+
+ @Override
+ protected boolean verify() {
+ return true;
+ }
+
+ @Override
+ public void storeReplica(Message m) {
+
+ }
+
+}
68 src/main/java/com/yahoo/paxos/client/messages/Submit.java
@@ -0,0 +1,68 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License. See accompanying LICENSE file.
+ */
+
+package com.yahoo.paxos.client.messages;
+
+import com.yahoo.pasc.Message;
+import com.yahoo.pasc.MessageDescriptor;
+
+public class Submit extends Message {
+
+ public static class Descriptor implements MessageDescriptor {
+
+ private byte[] value;
+
+ public Descriptor(byte[] value) {
+ this.value = value;
+ }
+
+ public byte[] getValue() {
+ return value;
+ }
+
+ public void setValue(byte[] value) {
+ this.value = value;
+ }
+ }
+
+ byte[] request;
+
+ public Submit() {
+ }
+
+ public Submit(byte[] request) {
+ this.request = request;
+ }
+
+ public byte[] getRequest() {
+ return request;
+ }
+
+ public void setRequest(byte[] request) {
+ this.request = request;
+ }
+
+ @Override
+ protected boolean verify() {
+ return true;
+ }
+
+ @Override
+ public void storeReplica(Message m) {
+
+ }
+
+}
50 src/main/java/com/yahoo/paxos/client/messages/Timeout.java
@@ -0,0 +1,50 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License. See accompanying LICENSE file.
+ */
+
+package com.yahoo.paxos.client.messages;
+
+import com.yahoo.pasc.Message;
+
+public class Timeout extends Message {
+
+ private long timestamp;
+
+ public Timeout() {
+ }
+
+ public Timeout(long timestamp) {
+ this.timestamp = timestamp;
+ }
+
+ public long getTimestamp() {
+ return timestamp;
+ }
+
+ public void setTimestamp(long timestamp) {
+ this.timestamp = timestamp;
+ }
+
+ @Override
+ protected boolean verify() {
+ return true;
+ }
+
+ @Override
+ public void storeReplica(Message m) {
+
+ }
+
+}
100 src/main/java/com/yahoo/paxos/handlers/DigestHandler.java
@@ -0,0 +1,100 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License. See accompanying LICENSE file.
+ */
+
+package com.yahoo.paxos.handlers;
+
+import java.util.List;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.yahoo.pasc.Message;
+import com.yahoo.paxos.messages.Digest;
+import com.yahoo.paxos.messages.PaxosDescriptor;
+import com.yahoo.paxos.state.DigestStore;
+import com.yahoo.paxos.state.PaxosState;
+
+public class DigestHandler extends PaxosHandler<Digest> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(DigestHandler.class);
+
+ @Override
+ public boolean guardPredicate(Message receivedMessage) {
+ return receivedMessage instanceof Digest;
+ }
+
+ @Override
+ public List<PaxosDescriptor> processMessage(Digest digest, PaxosState state) {
+
+// LOG.trace("Received digest {}.", digest);
+
+ storeDigest(digest.getDigestId(), digest.getDigest(), false, state);
+ return null;
+ }
+
+ public static void storeDigest(long digestId, long digest, boolean mine, PaxosState state) {
+ long firstDigestId = state.getFirstDigestId();
+ int maxDigests = state.getMaxDigests();
+
+// LOG.trace("Storing digest {} id {} mine {}.", new Object[] {digest, digestId, mine});
+
+ if (digestId < firstDigestId) {
+// LOG.trace("Ignoring digest for id {}, first digest: {}.", digestId, firstDigestId);
+ // ignore it
+ return;
+ } else if (firstDigestId + maxDigests <= digestId) {
+ LOG.error("We reached a checkpoint but have no space for its digest {}.", digest);
+ return;
+ }
+
+ DigestStore store = state.getDigestStoreElement(digestId);
+ int servers = state.getServers();
+ if (store == null || store.getDigestId() != digestId) {
+// LOG.trace("New store. (Old one: {})", store);
+ store = new DigestStore(digestId, servers);
+ state.setDigestStoreElement(digestId, store);
+ }
+ if (mine) {
+ store.addMine(digest);
+ } else {
+ store.addRemote(digest);
+ }
+
+ raiseFirstDigest(state);
+ }
+
+ public static void raiseFirstDigest(PaxosState state) {
+ long firstInstanceId = state.getFirstInstanceId();
+ int checkpointPeriod = state.getCheckpointPeriod();
+ int quorum = state.getDigestQuorum();
+ long firstDigestId = state.getFirstDigestId();
+ DigestStore store = state.getDigestStoreElement(firstDigestId);
+ while (store.matches(quorum)) {
+// LOG.trace("Matching digest {} ", firstDigestId);
+ firstInstanceId = firstDigestId * checkpointPeriod + 1;
+// LOG.trace("Setting first instance id to {}", firstInstanceId);
+ firstDigestId++;
+
+ store = state.getDigestStoreElement(firstDigestId);
+ if (store == null || store.getDigestId() < firstDigestId) {
+ store = new DigestStore(firstDigestId, state.getServers());
+ state.setDigestStoreElement(firstDigestId, store);
+ }
+ }
+ state.setFirstDigestId(firstDigestId);
+ state.setFirstInstanceId(firstInstanceId);
+ }
+}
50 src/main/java/com/yahoo/paxos/handlers/PaxosHandler.java
@@ -0,0 +1,50 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License. See accompanying LICENSE file.
+ */
+
+package com.yahoo.paxos.handlers;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import com.yahoo.pasc.Message;
+import com.yahoo.pasc.MessageHandler;
+import com.yahoo.paxos.messages.PaxosDescriptor;
+import com.yahoo.paxos.messages.PaxosMessage;
+import com.yahoo.paxos.state.PaxosState;
+
+public abstract class PaxosHandler<M extends PaxosMessage>
+ implements MessageHandler<M, PaxosState, PaxosDescriptor> {
+
+ @Override
+ public List<Message> getSendMessages(PaxosState state, List<PaxosDescriptor> descriptors) {
+ if (descriptors == null)
+ return null;
+
+ List<Message> messages = null;
+ for (PaxosDescriptor desc : descriptors) {
+ if (desc != null) {
+ List<PaxosMessage> generated = desc.buildMessages(state);
+ if (generated != null && !generated.isEmpty()) {
+ if (messages == null)
+ messages = new ArrayList<Message>(generated);
+ else
+ messages.addAll(generated);
+ }
+ }
+ }
+ return messages;
+ }
+}
129 src/main/java/com/yahoo/paxos/handlers/acceptor/AcceptorAccept.java
@@ -0,0 +1,129 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License. See accompanying LICENSE file.
+ */
+
+package com.yahoo.paxos.handlers.acceptor;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.yahoo.pasc.Message;
+import com.yahoo.paxos.handlers.PaxosHandler;
+import com.yahoo.paxos.handlers.proposer.ProposerRequest;
+import com.yahoo.paxos.messages.Accept;
+import com.yahoo.paxos.messages.Accepted;
+import com.yahoo.paxos.messages.PaxosDescriptor;
+import com.yahoo.paxos.state.ClientTimestamp;
+import com.yahoo.paxos.state.IidAcceptorsCounts;
+import com.yahoo.paxos.state.IidRequest;
+import com.yahoo.paxos.state.PaxosState;
+
+public class AcceptorAccept extends PaxosHandler<Accept> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ProposerRequest.class);
+
+ @Override
+ public boolean guardPredicate(Message receivedMessage) {
+ return receivedMessage instanceof Accept;
+ }
+
+ @Override
+ public List<PaxosDescriptor> processMessage(Accept message, PaxosState state) {
+ if (state.getIsLeader()) return null;
+
+ int ballot = message.getBallot();
+ int currentBallot = state.getBallotAcceptor();
+ List<PaxosDescriptor> descriptors = new ArrayList<PaxosDescriptor>();
+ if (ballot < currentBallot) {
+ LOG.trace("Rejecting accept. msg ballot: {} current ballot: {}", ballot,
+ currentBallot);
+ // We promised not to accept ballots lower than our current ballot
+ return null;
+ }
+ long iid = message.getIid();
+ long firstInstanceId = state.getFirstInstanceId();
+
+ if (firstInstanceId <= iid && iid < firstInstanceId + state.getMaxInstances()) {
+// LOG.trace("Received valid accept: {} ", message);
+
+ ClientTimestamp [] cts = message.getValues();
+ byte[][] requests = message.getRequests();
+ int arraySize = message.getArraySize();
+ int countReceivedRequests = 0;
+ for (int i = 0; i < arraySize; ++i) {
+ if (requests != null && requests[i] != null) {
+ state.setReceivedRequest(cts[i], new IidRequest(iid, requests[i]));
+ countReceivedRequests++;
+ } else {
+ IidRequest request = state.getReceivedRequest(cts[i]);
+ if (request == null || (request.getIid() != -1 && request.getIid() < firstInstanceId)) {
+ // LOG.trace("Creating new request (Old one: {}) ", request);
+ request = new IidRequest(iid);
+ state.setReceivedRequest(cts[i], request);
+ } else if (request.getRequest() != null && request.getIid() == -1) {
+ request.setIid(iid);
+ countReceivedRequests++;
+ } else {
+ LOG.warn("The acceptor created this request. Duplicated accept?");
+ }
+ }
+ }
+ IidAcceptorsCounts accepted = state.getAcceptedElement(iid);
+ if (accepted == null || accepted.getIid() != iid) {
+// LOG.trace("Initializing accepted for iid {}", iid);
+ accepted = new IidAcceptorsCounts(iid);
+ state.setAcceptedElement(iid, accepted);
+ }
+ accepted.setReceivedRequests(countReceivedRequests);
+ accepted.setTotalRequests(arraySize);
+ state.setInstancesElement(iid, message.getInstance());
+
+ checkAccept(iid, accepted, state, descriptors);
+
+ return descriptors;
+ } else {
+// LOG.warn("Received invalid accept: {} iid: {} firstIid: {} maxInst: {}", new Object[] { message, iid, firstInstanceId, state.getMaxInstances() });
+ }
+ return null;
+ }
+
+ public static void checkAccept(long iid, PaxosState state, List<PaxosDescriptor> descriptors) {
+ checkAccept(iid, null, state, descriptors);
+ }
+
+ public static void checkAccept(long iid, IidAcceptorsCounts accepted, PaxosState state, List<PaxosDescriptor> descriptors) {
+ if (accepted == null) {
+ // Called from proposer, a new request has been received
+ accepted = state.getAcceptedElement(iid);
+ accepted.setReceivedRequests(accepted.getReceivedRequests() + 1);
+ }
+
+ int receivedRequests = accepted.getReceivedRequests();
+ int totalRequests = accepted.getTotalRequests();
+ if (receivedRequests == totalRequests) {
+ accepted.setAccepted(true);
+
+ descriptors.add(new Accepted.Descriptor(iid));
+
+// Learner.checkExecute(iid, state, descriptors);
+// } else {
+// LOG.trace("Only received {} requests but need {} to accept this instance", receivedRequests,
+// totalRequests);
+ }
+ }
+}
41 src/main/java/com/yahoo/paxos/handlers/acceptor/AcceptorPrepare.java
@@ -0,0 +1,41 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License. See accompanying LICENSE file.
+ */
+
+package com.yahoo.paxos.handlers.acceptor;
+
+import java.util.List;
+
+import com.yahoo.pasc.Message;
+import com.yahoo.paxos.handlers.PaxosHandler;
+import com.yahoo.paxos.messages.PaxosDescriptor;
+import com.yahoo.paxos.messages.Prepare;
+import com.yahoo.paxos.state.PaxosState;
+
+public class AcceptorPrepare extends PaxosHandler<Prepare> {
+
+ // private static final Log LOG = LogFactory.getLog(AcceptorPrepare.class);
+
+ @Override
+ public boolean guardPredicate(Message receivedMessage) {
+ return receivedMessage instanceof Prepare;
+ }
+
+ @Override
+ public List<PaxosDescriptor> processMessage(Prepare message, PaxosState state) {
+ return null;
+ }
+
+}
120 src/main/java/com/yahoo/paxos/handlers/learner/Learner.java
@@ -0,0 +1,120 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License. See accompanying LICENSE file.
+ */
+
+package com.yahoo.paxos.handlers.learner;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.yahoo.pasc.Message;
+import com.yahoo.paxos.handlers.PaxosHandler;
+import com.yahoo.paxos.handlers.proposer.ProposerRequest;
+import com.yahoo.paxos.messages.Accepted;
+import com.yahoo.paxos.messages.Execute;
+import com.yahoo.paxos.messages.PaxosDescriptor;
+import com.yahoo.paxos.state.IidAcceptorsCounts;
+import com.yahoo.paxos.state.PaxosState;
+
+public class Learner extends PaxosHandler<Accepted> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(Learner.class);
+
+ @Override
+ public boolean guardPredicate(Message receivedMessage) {
+ return receivedMessage instanceof Accepted;
+ }
+
+ @Override
+ public List<PaxosDescriptor> processMessage(Accepted message, PaxosState state) {
+ long iid = message.getIid();
+ long firstInstanceId = state.getFirstInstanceId();
+ int maxInstances = state.getMaxInstances();
+ if (iid < firstInstanceId || firstInstanceId + maxInstances <= iid) {
+// LOG.warn("Rejecting accepted. firstId: {} iid: {}", firstInstanceId, iid);
+ return null;
+ }
+ // TODO check this
+ long currentBallot = state.getBallotAcceptor();
+ long ballot = message.getBallot();
+ if (ballot < currentBallot) {
+ LOG.warn("Rejecting accepted. msg ballot: {} current ballot: {}", ballot,
+ currentBallot);
+ return null;
+ }
+ List<PaxosDescriptor> descriptors = new ArrayList<PaxosDescriptor>();
+
+ IidAcceptorsCounts instance = state.getAcceptedElement(iid);
+ if (instance == null || instance.getIid() != iid) {
+ instance = new IidAcceptorsCounts(iid);
+ state.setAcceptedElement(iid, instance);
+ }
+ instance.setAcceptor(message.getSenderId());
+
+ checkExecute(iid, state, descriptors, null);
+
+ return descriptors;
+ }
+
+ public static void checkExecute(long checkIid, PaxosState state, List<PaxosDescriptor> descriptors) {
+ checkExecute(checkIid, state, descriptors, null);
+ }
+
+ public static void checkExecute(long checkIid, PaxosState state, List<PaxosDescriptor> descriptors, Accepted msg) {
+// LOG.trace("Checking if instance {} is learned with message {}.", checkIid, msg);
+ long maxExecuted = state.getMaxExecuted();
+ long firstInstanceId = state.getFirstInstanceId();
+ int maxInstances = state.getMaxInstances();
+ int quorum = state.getQuorum();
+ int servers = state.getServers();
+ boolean isLeader = state.getIsLeader();
+
+ for (long iid = checkIid; iid < firstInstanceId + maxInstances; ++iid) {
+// LOG.trace("Checking instance {}.", iid);
+ if (iid != maxExecuted + 1) {
+// LOG.trace("Next instance to be executed is {} and we are at {}", maxExecuted + 1, iid);
+ return;
+ }
+
+ IidAcceptorsCounts instance = state.getAcceptedElement(iid);
+ if (instance == null || instance.getIid() != iid) {
+ return;
+ }
+ if (instance.isAccepted() && instance.getCardinality(servers) >= quorum) {
+// LOG.trace("This instance has been accepted.");
+
+
+ if (isLeader) {
+// LOG.trace("Decrement pending.");
+ ProposerRequest.decrementPending(state, descriptors);
+ }
+
+ // execute instance
+// LOG.trace("Execute instance " + iid);
+ maxExecuted++;
+ state.setMaxExecuted(maxExecuted);
+ descriptors.add(new Execute.Descriptor(iid));
+ } else {
+// if (instance.isAccepted())
+// LOG.trace("This instance doesn't have a quorum of accepts yet.");
+// else
+// LOG.trace("This instance hasn't been accepted yet.");
+ }
+ }
+ }
+}
74 src/main/java/com/yahoo/paxos/handlers/learner/LearnerPreReply.java
@@ -0,0 +1,74 @@
+/**
+ * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License. See accompanying LICENSE file.
+ */
+
+package com.yahoo.paxos.handlers.learner;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.yahoo.pasc.Message;
+import com.yahoo.paxos.handlers.DigestHandler;
+import com.yahoo.paxos.handlers.PaxosHandler;
+import com.yahoo.paxos.messages.Digest;
+import com.yahoo.paxos.messages.PaxosDescriptor;
+import com.yahoo.paxos.messages.PreReply;
+import com.yahoo.paxos.messages.Reply;
+import com.yahoo.paxos.state.PaxosState;
+import com.yahoo.paxos.state.TimestampReply;
+
+public class LearnerPreReply extends PaxosHandler<PreReply> {
+
+ @SuppressWarnings("unused")
+ private static final Logger LOG = LoggerFactory.getLogger(LearnerPreReply.class);
+
+ @Override
+ public boolean guardPredicate(Message receivedMessage) {
+ return receivedMessage instanceof PreReply;
+ }
+
+ @Override
+ public List<PaxosDescriptor> processMessage(PreReply message, PaxosState state) {
+ int clientId = message.getClientId();
+ long timestamp = message.getTimestamp();
+// LOG.trace("Received {}", message);
+ state.setReplyCacheElement(clientId, new TimestampReply(timestamp, message.getReply()));
+ List<PaxosDescriptor> descriptors = null;
+ Long digest = message.getDigest();
+ if (digest != null) {
+ long iid = message.getIid();
+// LOG.trace("Processing digest for ct {} and iid {}", ct, iid);
+ long checkpointPeriod = state.getCheckpointPeriod();
+ // only send digests to other servers if we have to coordinate them
+ if (state.getDigestQuorum() > 1) {
+ if (descriptors == null)
+ descriptors = new ArrayList<PaxosDescriptor>(2);
+ descriptors.add(new Digest.Descriptor(iid / checkpointPeriod, digest));
+ }
+
+ DigestHandler.storeDigest(iid / checkpointPeriod, digest, true, state);