lib/service.rb in servicy-0.0.3 vs lib/service.rb in servicy-0.0.5
- old
+ new
@@ -2,11 +2,11 @@
module Servicy
class Service
include Comparable
attr_reader :name, :version, :host, :port, :heartbeat_port, :protocol,
- :api, :heartbeat_check_rate, :latencies, :heartbeats
+ :api, :heartbeat_check_rate, :latencies, :heartbeats, :no_heartbeat
attr_accessor :heartbeat_last_check
NAME_REGEX = /[^\.]+\.([^\.]+\.?)+/
VERSION_REGEX = /\d+\.\d+\.\d+(-p?\d+)?/
@@ -48,13 +48,18 @@
@protocol = args[:protocol]
@port = args[:port]
@heartbeat_port = args[:heartbeat_port]
@api = args[:api] || {}
@heartbeat_check_rate = args[:heartbeat_check_rate] || 1
+ @transport = transport_from_class_or_string(args[:protocol] || Servicy.config.client.transport)
+ if @transport
+ args[:protocol] = @transport.protocol_string # This is to make sure that it loads correctly after saving to disk.
+ end
@heartbeat_last_check = 0
@latencies = []
@heartbeats = []
+ @no_heartbeat = !!args[:no_heartbeat]
end
# Get a configuration value
# This method exists mostly so that I wouldn't have to change a bunch of
# early tests, and because I know some people like to access things like a
@@ -97,16 +102,17 @@
# (see #version_as_number)
# @param [String] A version string as per {Servicy::Server#register}
def self.version_as_number(version)
parts = version.split('.')
parts.last.gsub(/\D/, '')
- parts[0].to_i * 1000 + parts[1].to_i * 100 + parts[2].to_i * 10 + (parts[3] || 0)
+ parts[0].to_i * 1000 + parts[1].to_i * 100 + parts[2].to_i * 10 + (1 / (parts[3] || 1).to_f)
end
# Check weather or not a service is up, based on connecting to the hearbeat
# port, and reading a single byte.
def up?
+ return true if skip_heartbeat?
t1 = Time.now
s = TCPSocket.new(host, heartbeat_port)
Timeout.timeout(5) do
s.recvfrom(1)
end
@@ -159,14 +165,40 @@
# found.
def api_for(method_type, method)
api[method_type] && api[method_type].select { |a| a[:name] == method }.first
end
+ # Make a call to a remote end-point.
+ def remote_call(method, *args)
+ # TODO: think about handling errors in a sane way
+
+ # Encode things for the transports formatter
+ args = @transport.format(args)
+
+ # Make the call
+ @transport.remote_request(method, args)
+
+ # Decode things coming back
+ @transport.unformat(result)
+ end
+
private
+ def skip_heartbeat?
+ !!no_heartbeat
+ end
+
+ def transport_from_class_or_string(transport)
+ transport.is_a?(Servicy::Transport) ? transport : transport_from_string(transport)
+ end
+
+ def transport_from_string(transport)
+ Servicy::Transport.all.select { |t| t.protocol_string == transport }.first
+ end
+
# These are just to keep us from filling up memory.
def record_latency(t1, t2)
- @latencies << t2 - t1
+ @latencies << t2.to_i - t1.to_i
@latencies = @latencies[0...10] if @latencies.length > 10
end
def record_heartbeat(h)
@heartbeats << h