Class: HostList

Inherits:
Object
  • Object
show all
Defined in:
lib/hostlist.rb

Instance Method Summary collapse

Constructor Details

#initialize(yaml: '/etc/hostlist.yaml', cache: '~/.hostlist.db') ⇒ HostList

Returns a new instance of HostList.



8
9
10
11
# File 'lib/hostlist.rb', line 8

def initialize(yaml: '/etc/hostlist.yaml', cache: '~/.hostlist.db')
  @yaml = yaml
  @db_filename = cache
end

Instance Method Details

#generate_db(db) ⇒ Object



73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/hostlist.rb', line 73

def generate_db(db)
  db.clear
  db[:all] = []
  hosts = YAML.load_file(@yaml)
  hosts.each do |key, value|
    value['tags'].each do |tag|
      if db.has_key? tag
        db[tag] += key.expand
      else
        db[tag] = key.expand
      end
    end
    # Add servers to :all
    # TODO: Figure out why this isn't working. db[:all] is always an empty array.
    key.expand.each { |host| db[:all] += [host] unless db[:all].include?(host) }
  end
  db[:md5] = Digest::MD5.file(@yaml).to_s
  db.flush
end

#keysObject

Return all the keys in the database.



47
48
49
50
51
52
53
54
55
# File 'lib/hostlist.rb', line 47

def keys
  db = open_db
  begin
    keys = db.keys
  ensure
    db.close
  end
  return keys
end

#list(tags) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/hostlist.rb', line 13

def list(tags)
  tags = [tags] if tags.is_a? String
  # Verify we have the most recent data in our daybreak cache.
  db = open_db
  begin
    if db.has_key? :md5
      file_md5 = Digest::MD5.file @yaml
      generate_db(db) unless file_md5 == db[:md5]
    else
      generate_db(db)
    end
    db.load
    # Collect all the tags from the database
    hosts = []
    if tags.empty?
      hosts = db[:all]
    else
      tags.each do |tag|
        if db.has_key? tag
          if hosts == []
            hosts = db[tag]
          else
            hosts = hosts & db[tag]
          end
        end
      end
    end
  ensure
    db.close
  end
  return hosts
end

#open_dbObject



69
70
71
# File 'lib/hostlist.rb', line 69

def open_db
  Daybreak::DB.new File.expand_path(@db_filename)
end

Print the contents of the database for debugging purposes



58
59
60
61
62
63
64
65
66
67
# File 'lib/hostlist.rb', line 58

def print_db
  db = open_db
  begin
    db.keys.each do |key|
      puts "db[#{key}] = #{db[key]}"
    end
  ensure
    db.close
  end
end