g5k_generator.rb 9.2 KB
Newer Older
1
2
require 'resolv'

Cyril Rohr's avatar
Cyril Rohr committed
3
module G5K
4
  
Cyril Rohr's avatar
Cyril Rohr committed
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
  class Tree < Hash
    attr_reader :contents, :path
    def write(repository, &block)
      self[:uid] ||= ""
      @contents = {}
      @path = File.join(repository, self[:uid]+".json")
      self.each do |key, value|
        if value.is_a? Folder
          value.write(File.join(repository, self[:uid], key.to_s), &block)
          @path = File.join(repository, self[:uid], self[:uid]+".json")
        else
          @contents.merge!(key => value)
        end
      end
      if !@contents.empty? && !@contents[:uid].empty?
        yield self
      end
    end
    
    def valid?
      true
26
      # we could do sthg like: Object.const_get(type.class.name).new(hash_values).valid?
Cyril Rohr's avatar
Cyril Rohr committed
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
    end
  end
  class Folder < Array
    attr_reader :path
    def write(repository, &block)
      @path = repository
      self.each do |v| 
        v.write(repository, &block)
      end
      yield self
    end
    def valid?
      true
    end
  end
  class Link < Struct.new(:uid, :refer_to)
    attr_reader :from, :path
  
    def write(repository)
      @from, @path = [refer_to, File.join(repository, "#{uid}.json")]
      yield self
    end
    def valid?
      true
    end
  end

54
55
56
57
  class ReferenceGenerator  
    attr_reader :data
    attr_reader :config
    attr_reader :input
Cyril Rohr's avatar
Cyril Rohr committed
58
  
59
60
61
    def method_missing(method, *args)
      @context.recursive_merge!(method.to_sym => args.first)
    end
Gaetan SIMO's avatar
Gaetan SIMO committed
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

    # Remotly execute commands, and retrieve stdout, stderr, exit code and exit signal.
    def ssh_exec!(ssh, command)
      stdout_data = ""
      stderr_data = ""
      exit_code = nil
      exit_signal = nil
      ssh.open_channel do |channel|
        channel.exec(command) do |ch, success|
          unless success
            abort "FAILED: couldn't execute command (ssh.channel.exec)"
          end
          channel.on_data do |ch,data|
            stdout_data+=data
          end
          
          channel.on_extended_data do |ch,type,data|
            stderr_data+=data
          end
          
          channel.on_request("exit-status") do |ch,data|
            exit_code = data.read_long
          end
          
          channel.on_request("exit-signal") do |ch, data|
            exit_signal = data.read_long
          end
        end
      end
      ssh.loop
      [stdout_data, stderr_data, exit_code, exit_signal]
    end  
  
    # Get the IP address corresponding to the host fqdn throught ssh channel
    def dns_lookup_through_ssh(ssh,fqdn)
      results = ssh_exec! ssh, "host #{fqdn}"
      if results[2] == 0
        results[0].split(" ").reverse[0]
      else
        fail "Failed to get ip address of '#{fqdn}' : #{results[1]}"
      end
    end
Cyril Rohr's avatar
Cyril Rohr committed
104
  
105
106
107
    def dns_lookup(network_address)
      Resolv.getaddress(network_address)
    end
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
    # Lookup a key in one of the configuration files passed to the generator
    #
    # Usage:
    #   lookup('nancy', 'nodes', 'paramount-1', 'property_name')
    # or
    #   lookup('nancy', 'nodes') { |result| result['paramount-1']['property_name'] }
    # or
    #   lookup('nancy') { |result| result['nodes']['paramount-1']['property_name'] }
    # 
    # assuming you passed a <tt>nancy.yaml</tt> file to the generator
    #
    def lookup(filename, *keys, &block)
      if config.has_key?(filename)
        result = config[filename]
        if !keys.empty?
          while !keys.empty? do
            result = result[keys.shift]
            break if result.nil?
          end
        end  
        if block
          block.call(result) 
        else
          result
133
134
        end
      else
135
        raise ArgumentError, "Cannot fetch the values for '#{keys.inspect}' in the input file '#{filename}'. The config files you gave to me are: '#{config.keys.inspect}'."
136
137
      end
    end
Gaetan SIMO's avatar
Gaetan SIMO committed
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
    
    # This method is used exclusivly for environments. Example:
    # environment 'squeeze-x64-xen-0.8' do
    #  available_on %w{bordeaux grenoble lille lyon nancy orsay rennes sophia toulouse}
    # end    
    def available_on(sites_uid)
      env_uid = @context[:uid]
      old_context = @context 
      @context = @data
      sites_uid.each{|site_uid|
        site site_uid.to_sym, {:discard_content => true} do
          environment "#{env_uid}", :refer_to => "grid5000/environments/#{env_uid}"    
        end
      }
      @context = old_context
    end
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
    # This doesn't work with Ruby < 1.8.7. Replaced by a call to build_context (see below).
    #
    # %w{site cluster environment node service}.each do |method|
    #   define_method(method) do |uid, *options, &block|
    #     key = method.pluralize.to_sym
    #     uid = uid.to_s
    #     options = options.first || Hash.new
    #     old_context = @context
    #     @context[key] ||= G5K::Folder.new
    #     if options.has_key? :refer_to
    #       @context[key] << G5K::Link.new(uid, options[:refer_to])
    #     else    
    #       # if the same object already exists, we return it for completion/modification
    #       if (same_trees = @context[key].select{|tree| tree[:uid] == uid}).size > 0
    #         @context = same_trees.first
    #       else
    #         @context[key] << G5K::Tree.new.replace({:uid => uid, :type => method})
    #         @context = @context[key].last
    #       end
    #       block.call(uid) if block
    #     end
    #     @context = old_context
    #   end
    # end
178
  
179
180
181
182
183
184
185
186
187
188
189
190
    def site(uid, *options, &block)
      build_context(:sites, uid, *options, &block)
    end
    def cluster(uid, *options, &block)
      build_context(:clusters, uid, *options, &block)
    end
    def server(uid, *options, &block)
      build_context(:servers, uid, *options, &block)
    end
    def environment(uid, *options, &block)
      build_context(:environments, uid, *options, &block)
    end
191
192
193
    def network_equipment(uid, *options, &block)
      build_context(:network_equipments, uid, *options, &block)
    end
194
195
196
    def node(uid, *options, &block)
      build_context(:nodes, uid, *options, &block)
    end
197
198
199
    # def pdu(uid, *options, &block)
    #   build_context(:pdus, uid, *options, &block)
    # end
200
201
202
    def service(uid, *options, &block)
      build_context(:services, uid, *options, &block)
    end
203
204
205
    def network_equipment(uid, *options, &block)
      build_context(:network_equipments, uid, *options, &block)
    end
206
207
208
209
210
211
212
213
214
215
216
217
218
    def build_context(key, uid, *options, &block)
      type = key.to_s.chop
      uid = uid.to_s
      options = options.first || Hash.new
      old_context = @context
      @context[key] ||= G5K::Folder.new
      if options.has_key? :refer_to
        @context[key] << G5K::Link.new(uid, options[:refer_to])
      else    
        # if the same object already exists, we return it for completion/modification
        if (same_trees = @context[key].select{|tree| tree[:uid] == uid}).size > 0
          @context = same_trees.first
        else
219
          @context[key] << G5K::Tree.new.replace({:uid => uid, :type => type}.merge((options[:discard_content]) ? {:discard_content => true} : {}))
220
221
222
          @context = @context[key].last
        end
        block.call(uid) if block
Cyril Rohr's avatar
Cyril Rohr committed
223
      end
224
      @context = old_context
Cyril Rohr's avatar
Cyril Rohr committed
225
226
    end
  
227
228
229
230
231
232
233
234
    # Initializes a new generator that will generate data files in a hierachical way. 
    # The root of the tree will be named with the value of <tt>data_description[:uid]</tt>.
    def initialize(data_description = {:uid => ""}, options = {:input => {}, :config => {}})
      @input = options[:input]
      raise(ArgumentError, "INPUT cannot be null or empty.") if input.nil? || input.empty?
      @config = options[:config] || {}
      @data = G5K::Tree.new.replace(data_description)
      @context = @data
Cyril Rohr's avatar
Cyril Rohr committed
235
236
    end
  
237
238
239
    def generate
      input.each do |filename, content|
        eval(content)
Cyril Rohr's avatar
Cyril Rohr committed
240
      end
241
      @data
Cyril Rohr's avatar
Cyril Rohr committed
242
    end
243
244
245
246
247
  
    def write(repository, options = {:simulate => false})
      things_to_create = []
      @data.write("/") do |thing_to_create|
        things_to_create << thing_to_create if thing_to_create.valid?
Cyril Rohr's avatar
Cyril Rohr committed
248
      end
249
250
251
252
253
254
      groups = things_to_create.group_by{|thing| thing.class}
      groups.has_key?(G5K::Folder) and groups[G5K::Folder].each do |folder|
        full_path = File.join(repository, folder.path)
        unless File.exists?(full_path)
          puts "Directory to be written = \t#{full_path}"
          FileUtils.mkdir_p(full_path) unless options[:simulate]
255
        end
256
      end
257
258
259
260
261
      groups.has_key?(G5K::Tree) and groups[G5K::Tree].each do |file|
        full_path = File.join(repository, file.path)
        new_content = JSON.pretty_generate(file.contents)
        existing_content = File.exists?(full_path) ? File.open(full_path, "r").read : ""
        if new_content.hash != existing_content.hash
262
263
264
265
          unless file.has_key? :discard_content and file[:discard_content]
            puts "File to be written      = \t#{full_path}"
            File.open(full_path, "w+"){ |f| f << new_content  } unless options[:simulate]
          end
266
267
268
269
270
271
272
273
274
275
276
277
278
        end
      end
      groups.has_key?(G5K::Link) and groups[G5K::Link].each do |link|      
        FileUtils.cd(repository) do |dir|
          to = File.join(".", link.path)
          from = File.join([".."]*(to.count(File::SEPARATOR)-1), "#{link.from}.json")
          unless File.exists?(to)
            puts "Symbolic link to be written = \t#{to} -> #{from}"
            FileUtils.ln_s(from, to, :force => true) unless options[:simulate]
          end
        end
      end  
    end
Cyril Rohr's avatar
Cyril Rohr committed
279
  
280
  end
Pascal Morillon's avatar
Pascal Morillon committed
281
end