lib/flapjack/data/entity.rb in flapjack-0.6.43 vs lib/flapjack/data/entity.rb in flapjack-0.6.44
- old
+ new
@@ -1,7 +1,9 @@
#!/usr/bin/env ruby
+require 'flapjack/data/contact'
+
module Flapjack
module Data
class Entity
@@ -29,12 +31,13 @@
redis.set("entity_id:#{entity['name']}", entity['id'])
redis.hset("entity:#{entity['id']}", 'name', entity['name'])
redis.del("contacts_for:#{entity['id']}")
if entity['contacts'] && entity['contacts'].respond_to?(:each)
- entity['contacts'].each {|contact|
- redis.sadd("contacts_for:#{entity['id']}", contact)
+ entity['contacts'].each {|contact_id|
+ next if Flapjack::Data::Contact.find_by_id(contact_id, :redis => redis).nil?
+ redis.sadd("contacts_for:#{entity['id']}", contact_id)
}
end
else
# empty string is the redis equivalent of a Ruby nil, i.e. key with
# no value
@@ -60,16 +63,34 @@
entity_name = redis.hget("entity:#{entity_id}", 'name')
return if entity_name.nil? || entity_name.empty?
self.new(:name => entity_name, :id => entity_id, :redis => redis)
end
+ # NB: if we're worried about user input, https://github.com/mudge/re2
+ # has bindings for a non-backtracking RE engine that runs in linear
+ # time
def self.find_all_name_matching(pattern, options = {})
raise "Redis connection not set" unless redis = options[:redis]
- matched_entities = redis.keys('check:*').collect {|check|
- a, entity, c = check.split(':')
- match = (entity =~ /#{pattern}/) ? entity : nil
- }
- matched_entities.compact.sort.uniq
+ redis.keys('entity_id:*').inject([]) {|memo, check|
+ a, entity_name = check.split(':')
+ if (entity_name =~ /#{pattern}/) && !memo.include?(entity_name)
+ memo << entity_name
+ end
+ memo
+ }.sort
+ end
+
+ def contacts
+ contact_ids = @redis.smembers("contacts_for:#{id}")
+
+ if @logger
+ @logger.debug("#{contact_ids.length} contact(s) for #{id} (#{name}): " +
+ contact_ids.length)
+ end
+
+ contact_ids.collect {|c_id|
+ Flapjack::Data::Contact.find_by_id(c_id, :redis => @redis)
+ }.compact
end
def check_list
@redis.keys("check:#{@name}:*").map {|k| k =~ /^check:#{@name}:(.+)$/; $1}
end