Skip to content
This repository has been archived by the owner on Dec 7, 2018. It is now read-only.

Commit

Permalink
Initial commit.
Browse files Browse the repository at this point in the history
  • Loading branch information
aflatter committed May 14, 2013
0 parents commit 8ee591d
Show file tree
Hide file tree
Showing 16 changed files with 860 additions and 0 deletions.
18 changes: 18 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
*.gem
*.rbc
.bundle
.config
.yardoc
Gemfile.lock
InstalledFiles
_yardoc
coverage
doc/
lib/bundler/man
pkg
rdoc
spec/reports
test/tmp
test/version_tmp
tmp
.DS_Store
3 changes: 3 additions & 0 deletions .yardopts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
--markup=markdown
--charset=utf-8
lib/**/*.rb
11 changes: 11 additions & 0 deletions Gemfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
source 'https://rubygems.org'

# Specify your gem's dependencies in raft.gemspec
gemspec

gem 'celluloid', git: 'http://github.com/celluloid/celluloid'

This comment has been minimized.

Copy link
@halorgium

halorgium May 28, 2013

Contributor

You'll need to add celluloid-io and celluloid-zmq

This comment has been minimized.

Copy link
@aflatter

aflatter May 28, 2013

Author Member

To get access to master? They are already part of the gemspec.

This comment has been minimized.

Copy link
@halorgium

halorgium May 28, 2013

Contributor

It'll be using the released gems by default.

This comment has been minimized.

Copy link
@aflatter

aflatter via email May 28, 2013

Author Member

This comment has been minimized.

Copy link
@halorgium

halorgium May 28, 2013

Contributor

Except for a change in celluloid-io regarding the Latch implementation!


group :docs do
gem 'yard'
gem 'redcarpet'
end
22 changes: 22 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
Copyright (c) 2013 Alexander Flatter

MIT License

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 changes: 29 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Raft

TODO: Write a gem description

## Installation

Add this line to your application's Gemfile:

gem 'raft'

And then execute:

$ bundle

Or install it yourself as:

$ gem install raft

## Usage

TODO: Write usage instructions here

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Added some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
2 changes: 2 additions & 0 deletions Rakefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#!/usr/bin/env rake
require "bundler/gem_tasks"
5 changes: 5 additions & 0 deletions lib/raft.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
require "raft/version"

module Raft
# Your code goes here...
end
67 changes: 67 additions & 0 deletions lib/raft/log.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
require 'forwardable'
require 'raft'

# See Section 5.3.
class Raft::Log
extend Forwardable

def_delegators :entries, :[]

class Entry
# @return [Fixnum] When the entry was received by the leader.
attr_accessor :term

# @return [Object] A replicated state machine command.
attr_accessor :command

# @return [Boolean]
attr_accessor :committed

def committed?

end
end

# @return [Array<Entry>] The log's entries.
attr_accessor :entries

def initialize
self.entries = []
end

def append(prev_log_index, prev_log_term, new_entries)
if validate(prev_log_index, prev_log_term)
# Remove all entries after the previous one.
remove_starting_with(prev_log_index + 1)
entries.concat(new_entries)

true
else
false
end
end

def last_index
entries.size - 1
end

def last_term
entry = entries.last
entry ? entry.term : -1
end

def complete?(other_term, other_index)
(other_term > last_term) || (other_term == last_term && other_index >= last_index)
end

protected

def validate(index, term)
entry = entries[index]
entry && entry.term == term
end

def remove_starting_with(index)
entries.slice!(index..-1)
end
end
160 changes: 160 additions & 0 deletions lib/raft/node.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
# encoding: utf-8

require 'celluloid/zmq'
require 'raft/rpc'
require 'raft/log'

class Raft::Node
require 'raft/node/states'

include Celluloid::ZMQ
include Celluloid::Logger

# Default broadcast time.
# @see #broadcast_time
BROADCAST_TIME = 0.020

# Default election timeout.
# @see #election_timeout
ELECTION_TIMEOUT = (0.150..0.300)

# @return [Raft::Log] The replicated log.
attr_accessor :log

# @return [Hash]
attr_accessor :options

# @return [Array<String>] Peers as configured in this cluster.
attr_accessor :peers

# @return [Raft::Node::State::Base] The current state of this node.
attr_accessor :state

# @return [String] id of this node's candidate
attr_accessor :voted_for

# @return [Fixnum] The current term.
attr_accessor :term

# @return [Fixnum] Term of the last log entry.
attr_accessor :last_log_term

# @return [Fixnum] Index of the last log entry.
attr_accessor :last_log_index

# @return [Raft::RPC::Server]
attr_accessor :server

# @return [Raft::RPC::Client]
attr_accessor :client

def initialize(options = {})
self.options = options
self.term = 0
self.last_log_term = 0
self.last_log_index = 0
self.log = Raft::Log.new
end

def run
self.server = link(Raft::RPC::Server.new(options[:listen], &method(:handle_rpc)))
self.client = link(Raft::RPC::Client.new)
server.run
switch_state(:follower)
end

# Execute a command on the replicated state machine.
def execute(*args)
state.execute(*args)
end

def handle_rpc(command, payload)
state.handle_rpc(command, payload)
end

def switch_state(new_state)
current_state = state ? state.class.name.split('::').last.downcase : nil
info("[TRANSITION] #{current_state} => #{new_state}")

self.state.exit_state if state
self.state = State.const_get(new_state.to_s.capitalize).new(Actor.current)
self.state.enter_state
end

# Returns this node's id.
# @return [String]
def id
options[:listen]
end

# Returns peers in the cluster.
# @return [Array<String>]
def peers
options[:peers]
end

# Returns the cluster's quorum.
# @return [Fixnum]
def cluster_quorum
(cluster_size / 2) + 1
end

# Returns the number of nodes in the cluster.
# @return [Fixnum]
def cluster_size
options[:peers].size + 1
end

# The interval between heartbeats (in seconds). See Section 5.7.
#
# > The broadcast time must be an order of magnitude less than the election timeout so that leaders can reliably send
# > the heartbeat messages required to keep followers from starting elections.
#
# @return [Float]
def broadcast_time
options[:broadcast_time] || BROADCAST_TIME
end

# Election timeout as defined in Section 5.2.
#
# This timeout is used in multiple ways:
#
# * If a follower does not receive any activity, it starts a new election.
# * As a candidate, if the election does not resolve within this time, it is restarted.
#
# @return [Range<Float>]
def election_timeout
options[:election_timeout] || ELECTION_TIMEOUT
end

# A random timeout within {#election_timeout}.
# @return [Float]
def random_timeout
min, max = election_timeout.first, election_timeout.last

min + rand(max - min)
end

def validate_term(other_term)
if other_term < term
return false
end

if other_term > term
enter_new_term(other_term)
end

true
end

def enter_new_term(new_term = nil)
self.term = (new_term || term + 1)
self.voted_for = nil
end

%w(info debug warn error).each do |m|
define_method(m) do |str|
super("[#{id}] #{str}")
end
end
end
Loading

0 comments on commit 8ee591d

Please sign in to comment.