Class: ZMQ::Util

Inherits:
Object
  • Object
show all
Defined in:
lib/ffi-rzmq/util.rb

Overview

General utility methods.

Class Method Summary collapse

Class Method Details

.bind_to_random_tcp_port(host = '127.0.0.1', max_tries = 500) ⇒ Object

Attempts to bind to a random tcp port on host up to max_tries times. Returns the port number upon success or nil upon failure.



51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/ffi-rzmq/util.rb', line 51

def self.bind_to_random_tcp_port host = '127.0.0.1', max_tries = 500
  tries = 0
  rc = -1

  while !resultcode_ok?(rc) && tries < max_tries
    tries += 1
    random = random_port
    rc = socket.bind "tcp://#{host}:#{random}"
  end

  resultcode_ok?(rc) ? random : nil
end

.curve_keypairObject

Generate and return a CURVE public/private keypair

Raises an error if ZeroMQ is not configured for CURVE connections. Install libsodium if this is the case.



12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/ffi-rzmq/util.rb', line 12

def self.curve_keypair
  public_key = FFI::MemoryPointer.from_string(' ' * 41)
  private_key = FFI::MemoryPointer.from_string(' ' * 41)
  rc = LibZMQ.zmq_curve_keypair public_key, private_key

  if rc < 0
    raise NotSupportedError.new "zmq_curve_keypair" , rc, ZMQ::Util.errno,
      "Rebuild zeromq with libsodium to enable CURVE security options."
  end

  [public_key.read_string, private_key.read_string]
end

.errnoObject

Returns the errno as set by the libzmq library.



37
38
39
# File 'lib/ffi-rzmq/util.rb', line 37

def self.errno
  LibZMQ.zmq_errno
end

.error_check(source, result_code) ⇒ Object

:doc: Called to verify whether there were any errors during operation. If any are found, raise the appropriate #ZeroMQError.

When no error is found, this method returns true which is behavior used internally by #send and #recv.



71
72
73
74
75
76
77
78
# File 'lib/ffi-rzmq/util.rb', line 71

def self.error_check source, result_code
  if -1 == result_code
    raise_error source, result_code
  end

  # used by Socket::send/recv, ignored by others
  true
end

.error_stringObject

Returns a string corresponding to the currently set #errno. These error strings are defined by libzmq.



44
45
46
# File 'lib/ffi-rzmq/util.rb', line 44

def self.error_string
  LibZMQ.zmq_strerror(errno).read_string
end

.resultcode_ok?(rc) ⇒ Boolean

Returns true when rc is greater than or equal to 0, false otherwise.

We use the >= test because zmq_poll() returns the number of sockets that had a read or write event triggered. So, a >= 0 result means it succeeded.

Returns:

  • (Boolean)


31
32
33
# File 'lib/ffi-rzmq/util.rb', line 31

def self.resultcode_ok? rc
  rc >= 0
end