forked from rubber/rubber
/
instance.rb
325 lines (272 loc) · 9.14 KB
/
instance.rb
1
2
3
4
5
6
7
8
9
10
11
12
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
require 'yaml'
require 'monitor'
module Rubber
module Configuration
# Contains the ec2 instance configuration defined in instance.yml
#
class Instance
attr_reader :instance_storage, :artifacts
include Enumerable
include MonitorMixin
def initialize(instance_storage, opts={})
super()
@instance_storage = instance_storage
@opts = opts
@items = {}
@artifacts = {'volumes' => {}, 'static_ips' => {}}
@filters = Rubber::Util::parse_aliases(ENV['FILTER'])
@filters, @filters_negated = @filters.partition {|f| f !~ /^-/ }
@filters_negated = @filters_negated.collect {|f| f[1..-1] }
@filter_roles = Rubber::Util::parse_aliases(ENV['FILTER_ROLES'])
@filter_roles, @filter_roles_negated = @filter_roles.partition {|f| f !~ /^-/ }
@filter_roles_negated = @filter_roles_negated.collect {|f| f[1..-1] }
load()
end
def load(instance_storage=@instance_storage)
case instance_storage
when /file:(.*)/
location = $1
File.open(location, 'r') {|f| load_from_file(f) } if File.exist?(location)
when /storage:(.*)/
location = $1
bucket = location.split("/")[0]
key = location.split("/")[1..-1].join("/")
data = Rubber.cloud.storage(bucket).fetch(key)
StringIO.open(data, 'r') {|f| load_from_file(f) }
when /table:(.*)/
location = $1
load_from_table(location)
else
raise "Invalid instance_storage: #{instance_storage}\n" +
"Must be one of file:, table:, storage:"
end
end
def load_from_file(io)
item_list = YAML.load(io.read)
if item_list
item_list.each do |i|
if i.is_a? InstanceItem
@items[i.name] = i
elsif i.is_a? Hash
@artifacts.merge!(i)
end
end
end
end
def load_from_table(table_key)
Rubber.logger.debug{"Reading rubber instances from cloud table #{table_key}"}
store = Rubber.cloud.table_store(table_key)
items = store.find()
items.each do |name, data|
case name
when '_artifacts_'
@artifacts = data
else
ic = InstanceItem.from_hash(data.merge({'name' => name}))
@items[ic.name] = ic
end
end
end
def save(instance_storage=@instance_storage, backup=@opts[:backup])
synchronize do
case instance_storage
when /file:(.*)/
location = $1
File.open(location, 'w') {|f| save_to_file(f) }
when /storage:(.*)/
location = $1
bucket = location.split("/")[0]
key = location.split("/")[1..-1].join("/")
data = StringIO.open {|f| save_to_file(f); f.string }
Rubber.cloud.storage(bucket).store(key, data)
when /table:(.*)/
location = $1
save_to_table(location)
else
raise "Invalid instance_storage: #{instance_storage}\n" +
"Must be one of file:, table:, storage:"
end
end
save(backup, false) if backup
end
def save_to_file(io)
data = []
data.push(*@items.values)
data.push(@artifacts)
io.write(YAML.dump(data))
end
def save_to_table(table_key)
store = Rubber.cloud.table_store(table_key)
# delete all before writing to handle removals
store.find().each do |k, v|
store.delete(k)
end
# only write out non-empty artifacts
artifacts = @artifacts.select {|k, v| v.size > 0}
if artifacts.size > 0
store.put('_artifacts_', artifacts)
end
# write out all the instance data
@items.values.each do |item|
store.put(item.name, item.to_hash)
end
end
def [](name)
@items[name] || @items[name.gsub(/\..*/, '')]
end
# gets the instances for the given role. If options is nil, all roles
# match, otherwise the role has to have options that match exactly
def for_role(role_name, options=nil)
@items.values.find_all {|ic| ic.roles.any? {|r| r.name == role_name && (! options || r.options == options)}}
end
def filtered()
filtered_results = []
validate_filters()
if @filters.size == 0 && @filter_roles.size == 0
filtered_results.concat(@items.values)
else
@items.values.each do |ic|
filtered_results << ic if @filters.include?(ic.name)
filtered_results << ic if ic.roles.any? {|r| @filter_roles.include?(r.name)}
end
end
filtered_results.delete_if {|ic| @filters_negated.include?(ic.name) }
filtered_results.delete_if {|ic| ic.roles.any? {|r| @filter_roles_negated.include?(r.name)} }
return filtered_results
end
def validate_filters()
aliases = @items.values.collect{|ic| ic.name}
[@filters, @filters_negated].flatten.each do |f|
raise "Filter doesn't match any hosts: #{f}" if ! aliases.include?(f)
end
roles = all_roles
[@filter_roles, @filter_roles_negated].flatten.each do |f|
raise "Filter doesn't match any roles: #{f}" if ! roles.include?(f)
end
end
def all_roles()
@items.collect {|n, i| i.role_names}.flatten.uniq
end
def add(instance_item)
@items[instance_item.name] = instance_item
end
def remove(name)
@items.delete(name)
end
def each(&block)
@items.values.each &block
end
def size
@items.size
end
end
# The configuration for a single instance
class InstanceItem
attr_reader :name, :domain, :instance_id, :image_type, :image_id, :security_groups
attr_accessor :roles, :zone
attr_accessor :external_host, :external_ip
attr_accessor :internal_host, :internal_ip
attr_accessor :static_ip, :volumes, :partitions, :root_device_type
attr_accessor :spot_instance_request_id
attr_accessor :platform
def initialize(name, domain, roles, instance_id, image_type, image_id, security_group_list=[])
@name = name
@domain = domain
@roles = roles
@instance_id = instance_id
@image_type = image_type
@image_id = image_id
@security_groups = security_group_list
end
def self.from_hash(hash)
item = allocate
hash.each do |k, v|
sym = "@#{k}".to_sym
v = v.collect {|r| RoleItem.parse(r) } if k == 'roles'
item.instance_variable_set(sym, v)
end
return item
end
def to_hash
hash = {}
instance_variables.each do |iv|
name = iv.to_s.gsub(/^@/, '')
value = instance_variable_get(iv)
value = value.collect {|r| r.to_s } if name == 'roles'
hash[name] = value
end
return hash
end
def full_name
"#@name.#@domain"
end
def role_names()
roles.collect {|r| r.name}
end
def platform
# Deal with old instance configurations that don't have a platform value persisted.
@platform || 'linux'
end
def windows?
platform == 'windows'
end
end
# The configuration for a single role contained in the list
# of roles in InstanceItem
class RoleItem
attr_reader :name, :options
def self.expand_role_dependencies(roles, dependency_map, expanded=[])
roles = Array(roles)
if expanded.size == 0
common_deps = Array(dependency_map[RoleItem.new('common')])
roles.concat(common_deps)
end
roles.each do |role|
unless expanded.include?(role)
expanded << role
needed = dependency_map[role]
expand_role_dependencies(needed, dependency_map, expanded)
end
end
return expanded
end
def self.parse(str)
data = str.split(':')
role = Rubber::Configuration::RoleItem.new(data[0])
if data[1]
data[1].split(';').each do |pair|
p = pair.split('=')
val = case p[1]
when 'true' then true
when 'false' then false
else p[1] end
role.options[p[0]] = val
end
end
return role
end
def to_s
str = @name
@options.each_with_index do |kv, i|
str += (i == 0 ? ':' : ';')
str += "#{kv[0]}=#{kv[1]}"
end
return str
end
def initialize(name, options={})
@name = name
@options = options || {}
end
def eql?(rhs)
rhs && @name == rhs.name && @options == rhs.options
end
alias == eql?
def hash()
@name.hash
end
def <=>(rhs)
return @name <=> rhs.name
end
end
end
end