Skip to content

Instantly share code, notes, and snippets.

@kwilczynski
Last active February 28, 2017 02:42
Show Gist options
  • Save kwilczynski/d654c740aca728aa7cbe to your computer and use it in GitHub Desktop.
Save kwilczynski/d654c740aca728aa7cbe to your computer and use it in GitHub Desktop.
RabbitMQ Queue type for Serverspec
# rubocop:disable ClassVars
module Serverspec
module Type
class RabbitMQQueue < Base
def initialize(queue)
@queue = queue
end
def exist?
value.key? @queue
end
def running_state
value('state') == 'running'
end
def durable_queue
value('durable') || false
end
def auto_delete
value('auto_delete') || false
end
def virtual_host
value('virtual_host') || false
end
def to_s
format('RabbitMQ Queue "%s"', @queue)
end
private
def current_queues
# Get current execution backed.
backend = ::Specinfra.backend
# We rely on the command line tool for managing a RabbitMQ broker,
# see: https://www.rabbitmq.com/man/rabbitmqctl.1.man.html
rabbitmq_ctl = '/usr/sbin/rabbitmqctl'
# Collect virtual hosts first.
cmd =
[rabbitmq_ctl].tap do |o|
o << '-q'
o << 'list_vhosts'
end.join(' ')
virtual_hosts = backend.run_command(cmd).stdout.split("\n")
keys = %w(state durable auto_delete)
# Enumerate queues on per virtual host basis.
queues =
virtual_hosts.map do |v|
cmd =
[rabbitmq_ctl].tap do |o|
o << '-q'
o << 'list_queues'
o << format('-p %s', v)
o << Array('name') + keys
end.join(' ')
output = backend.run_command(cmd).stdout
[v, output.split("\n")]
end
# Parse output for each queue.
queues.each_with_object({}) do |(v, line), h|
line.each do |l|
name, *settings = l.split
settings.map! { |i| try_boolean(i) }
h[name] = Hash[keys.zip(settings)].update('virtual_host' => v)
end
end
end
def value(key = nil)
@@cache ||= current_queues
key ? @@cache.fetch(@queue, {})[key] : @@cache
end
def try_boolean(value)
case value
when /^(true|yes|1)$/
true
when /^(false|no|0)$/
false
else
value
end
end
end
def rabbitmq_queue(queue)
RabbitMQQueue.new(queue)
end
end
end
# rubocop:enable ClassVars
include Serverspec::Type
@kwilczynski
Copy link
Author

@johanek glad you found it useful :) No, but I am happy to look into bindings too, if you want?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment