Module: Resource

Included in:
Rbbt
Defined in:
lib/rbbt/resource.rb,
lib/rbbt/resource/util.rb,
lib/rbbt/resource/with_key.rb

Defined Under Namespace

Modules: WithKey

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, prev = nil, *args) ⇒ Object



43
44
45
46
47
48
49
# File 'lib/rbbt/resource.rb', line 43

def method_missing(name, prev = nil, *args)
  if prev.nil?
    root.send(name, *args)
  else
    root.send(name, prev, *args)
  end
end

Class Attribute Details

.lock_dirObject

Returns the value of attribute lock_dir.



11
12
13
# File 'lib/rbbt/resource.rb', line 11

def lock_dir
  @lock_dir
end

Instance Attribute Details

#pkgdirObject

Returns the value of attribute pkgdir.



32
33
34
# File 'lib/rbbt/resource.rb', line 32

def pkgdir
  @pkgdir
end

#rake_dirsObject

Returns the value of attribute rake_dirs.



32
33
34
# File 'lib/rbbt/resource.rb', line 32

def rake_dirs
  @rake_dirs
end

#remote_serverObject

Returns the value of attribute remote_server.



32
33
34
# File 'lib/rbbt/resource.rb', line 32

def remote_server
  @remote_server
end

#resourcesObject

Returns the value of attribute resources.



32
33
34
# File 'lib/rbbt/resource.rb', line 32

def resources
  @resources
end

#search_pathsObject

Returns the value of attribute search_paths.



32
33
34
# File 'lib/rbbt/resource.rb', line 32

def search_paths
  @search_paths
end

#server_missing_resource_cacheObject

Returns the value of attribute server_missing_resource_cache.



74
75
76
# File 'lib/rbbt/resource.rb', line 74

def server_missing_resource_cache
  @server_missing_resource_cache
end

#subdirObject

Returns the value of attribute subdir.



32
33
34
# File 'lib/rbbt/resource.rb', line 32

def subdir
  @subdir
end

Class Method Details

.extended(base) ⇒ Object



22
23
24
25
26
27
28
29
30
# File 'lib/rbbt/resource.rb', line 22

def self.extended(base)
  base.pkgdir = 'rbbt'
  base.subdir = ''
  base.resources = {}
  base.rake_dirs = {}
  base.search_paths = Path::SEARCH_PATHS.dup
  base.remote_server = Resource.remote_servers[base.to_s]
  base
end

.remote_serversObject



18
19
20
# File 'lib/rbbt/resource.rb', line 18

def self.remote_servers
  @remote_servers = Rbbt.etc.file_servers.exists? ? Rbbt.etc.file_servers.yaml : {}
end

Instance Method Details

#[](file = nil) ⇒ Object



51
52
53
54
55
56
57
# File 'lib/rbbt/resource.rb', line 51

def [](file = nil)
  if file.nil?
    root
  else
    root.send(file)
  end
end

#claim(path, type, content = nil, &block) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/rbbt/resource.rb', line 59

def claim(path, type, content = nil, &block)
  if type == :rake
    @rake_dirs[path] = content
  else
    @resources[path] = [type, content || block]

    if type == :install
      Log.debug "Preparing software: #{path}"
      path.produce
      software_dir = path.resource.root.software
      set_software_env(software_dir)
    end
  end
end

#get_from_server(path, final_path, remote_server = nil) ⇒ Object



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
# File 'lib/rbbt/resource.rb', line 75

def get_from_server(path, final_path, remote_server = nil)
  remote_server ||= self.remote_server
  remote_server = "http://" + remote_server unless remote_server =~ /^[a-z]+:\/\//
  url = File.join(remote_server, '/resource/', self.to_s, 'get_file')
  url << "?" << Misc.hash2GET_params(:file => path, :create => false)

  begin
    @server_missing_resource_cache ||= Set.new
    raise "Resource Not Found" if @server_missing_resource_cache.include? url
    
    #lock_filename = Persist.persistence_path(final_path, {:dir => Resource.lock_dir})
    
    lock_filename = nil # it seems like this was locked already.

    Misc.lock lock_filename do
      Net::HTTP.get_response URI(url) do |response|
        case response
        when Net::HTTPSuccess, Net::HTTPOK
          Misc.sensiblewrite(final_path) do |file|
            response.read_body do |chunk|
              file.write chunk
            end
          end
        when Net::HTTPRedirection, Net::HTTPFound
          location = response['location']
          Log.debug("Feching directory from: #{location}. Into: #{final_path}")
          FileUtils.mkdir_p final_path unless File.exist? final_path
          TmpFile.with_file do |tmp_dir|
            Misc.in_dir tmp_dir do
              CMD.cmd('tar xvfz -', :in => Open.open(location, :nocache => true))
            end
            FileUtils.mv tmp_dir, final_path
          end
        when Net::HTTPInternalServerError
          @server_missing_resource_cache << url
          raise "Resource Not Found"
        else
          raise "Response not understood: #{response.inspect}"
        end
      end
    end
  rescue
    Log.warn "Could not retrieve (#{self.to_s}) #{ path } from #{ remote_server }"
    Log.error $!.message
    FileUtils.rm_rf final_path if File.exist? final_path
    return false
  end
end

#has_rake(path) ⇒ Object



101
102
103
# File 'lib/rbbt/resource/util.rb', line 101

def has_rake(path)
  !! rake_for(path)
end

#produce(path, force = false) ⇒ Object



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
# File 'lib/rbbt/resource.rb', line 124

def produce(path, force = false)
  case
  when @resources.include?(path)
    type, content = @resources[path]
  when @resources.include?(path.original)
    type, content = @resources[path.original]
  when has_rake(path)
    type = :rake
    rake_dir, content = rake_for(path)
    rake_dir = Path.setup(rake_dir.dup, self.pkgdir, self)
  else
    begin
      if path !~ /\.(gz|bgz)$/
        begin
          produce(path + '.gz', force)
        rescue
          produce(path + '.bgz', force)
        end
      end
    rescue
      raise "Resource is missing and does not seem to be claimed: #{ self } -- #{ path } "
    end
  end

  if path.respond_to?(:find) 
    final_path = force ? path.find(:default) : path.find
  else
    final_path = path
  end

  if not File.exist? final_path or force
    Log.medium "Producing: #{ final_path }"
    lock_filename = Persist.persistence_path(final_path, {:dir => Resource.lock_dir})
    Misc.lock lock_filename do
      FileUtils.rm_rf final_path if force and File.exist? final_path
      if not File.exist? final_path or force
        (remote_server and get_from_server(path, final_path)) or
        begin
          case type
          when :string
            Misc.sensiblewrite(final_path, content)
          when :url
            options = {}
            options[:noz] = true if Open.gzip?(final_path) || Open.bgzip?(final_path) || Open.zip?(final_path)
            Misc.sensiblewrite(final_path, Open.open(content, options))
          when :proc
            data = case content.arity
                   when 0
                     content.call
                   when 1
                     content.call final_path
                   end
            case data
            when String, IO, StringIO
              Misc.sensiblewrite(final_path, data) 
            when Array
              Misc.sensiblewrite(final_path, data * "\n")
            when TSV
              Misc.sensiblewrite(final_path, data.dumper_stream) 
            when TSV::Dumper
              Misc.sensiblewrite(final_path, data.stream) 
            when nil
            else
              raise "Unkown object produced: #{Misc.fingerprint data}"
            end
          when :rake
            run_rake(path, content, rake_dir)
          when :install
            Log.debug "Installing software: #{path}"
            software_dir = path.resource.root.software.find :user
            helper_file = File.expand_path(Rbbt.share.install.software.lib.install_helpers.find(:lib, caller_lib_dir(__FILE__)))
            #helper_file = File.expand_path(Rbbt.share.install.software.lib.install_helpers.find)

            preamble = <<-EOF
#!/bin/bash

RBBT_SOFTWARE_DIR="#{software_dir}"

INSTALL_HELPER_FILE="#{helper_file}"
source "$INSTALL_HELPER_FILE"
            EOF

            script = preamble + "\n" + Open.read(content)
            CMD.cmd_log('bash', :in => script)

            set_software_env(software_dir)
          else
            raise "Could not produce #{ resource }. (#{ type }, #{ content })"
          end
        rescue
          FileUtils.rm_rf final_path if File.exist? final_path
          raise $!
        end
      end
    end
  end

  path
end

#rake_for(path) ⇒ Object



93
94
95
96
97
98
99
# File 'lib/rbbt/resource/util.rb', line 93

def rake_for(path)
  @rake_dirs.reject{|dir, content|
    !Misc.common_path(dir, path)
  }.sort_by{|dir, content|
    dir.length
  }.last
end

#rootObject



39
40
41
# File 'lib/rbbt/resource.rb', line 39

def root
  Path.setup @subdir || "", @pkgdir, self, @search_paths
end

#run_rake(path, rakefile, rake_dir) ⇒ Object



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/rbbt/resource/util.rb', line 105

def run_rake(path, rakefile, rake_dir)
  task = Misc.path_relative_to rake_dir, path
  rakefile = rakefile.produce if rakefile.respond_to? :produce

  rake_dir = rake_dir.find(:user) if rake_dir.respond_to? :find

  begin
    require 'rbbt/resource/rake'
    Rake.run(rakefile, rake_dir, task)
  rescue Rake::TaskNotFound
    raise $! if rake_dir.nil? or rake_dir.empty? or rake_dir == "/" or rake_dir == "./"
    task = File.join(File.basename(rake_dir), task)
    rake_dir = File.dirname(rake_dir)
    retry
  end
end

#set_libdir(value = nil) ⇒ Object



34
35
36
37
# File 'lib/rbbt/resource.rb', line 34

def set_libdir(value = nil)
  _libdir = value || Path.caller_lib_dir
  search_paths.merge!(:lib => File.join(_libdir, '{TOPLEVEL}', '{SUBPATH}'))
end

#set_software_env(software_dir) ⇒ Object



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
# File 'lib/rbbt/resource/util.rb', line 33

def set_software_env(software_dir)
  software_dir.find_all.each do |software_dir|
    next unless software_dir.exists?
    bin_dir = File.join(software_dir, 'bin')
    opt_dir = File.join(software_dir, 'opt')

    Misc.env_add 'PATH', bin_dir

    FileUtils.mkdir_p opt_dir unless File.exist? opt_dir

    %w(.ld-paths .c-paths .pkgconfig-paths .aclocal-paths .java-classpaths).each do |file|
      filename = File.join(opt_dir, file)
      begin
        FileUtils.touch filename unless File.exist? filename
      rescue
        Log.warn("Could not touch #{ filename }")
      end
    end

    Open.read(File.join opt_dir, '.c-paths').split(/\n/).each do |line|
      Misc.env_add('C_INCLULDE_PATH',line.chomp)
    end if File.exist? File.join(opt_dir, '.c-paths')

    Open.read(File.join opt_dir, '.ld-paths').split(/\n/).each do |line|
      Misc.env_add('LD_LIBRARY_PATH',line.chomp)
      Misc.env_add('LD_RUN_PATH',line.chomp)
    end if File.exist? File.join(opt_dir, '.ld-paths')

    Open.read(File.join opt_dir, '.pkgconfig-paths').split(/\n/).each do |line|
      Misc.env_add('PKG_CONFIG_PATH',line.chomp)
    end if File.exist? File.join(opt_dir, '.pkgconfig-paths')

    Open.read(File.join opt_dir, '.aclocal-paths').split(/\n/).each do |line|
      Misc.env_add('ACLOCAL_FLAGS', "-I#{File.join(opt_dir, line.chomp)}", ' ')
    end if File.exist? File.join(opt_dir, '.aclocal-paths')

    Open.read(File.join opt_dir, '.java-classpaths').split(/\n/).each do |line|
      Misc.env_add('CLASSPATH', "#{File.join(opt_dir,'java', 'lib', line.chomp)}")
    end if File.exist? File.join(opt_dir, '.java-classpaths')

    Dir.glob(File.join opt_dir, 'jars', '*').each do |file|
      Misc.env_add('CLASSPATH', "#{File.expand_path(file)}")
    end

    if File.exist?(File.join(opt_dir, '.post_install')) and File.directory?(File.join(opt_dir, '.post_install'))
      Dir.glob(File.join(opt_dir, '.post_install','*')).each do |file|
        begin
          begin
            File.chmod file
            CMD.cmd(file) 
          rescue
            Log.warn("Could not execute #{ file }")
          end
        end
      end
    end
  end
end

#with_key(key) ⇒ Object



20
21
22
23
24
25
26
27
# File 'lib/rbbt/resource/with_key.rb', line 20

def with_key(key)
  klass = self
  o     = Object.new
  o.extend WithKey
  o.klass = self
  o.key   = key
  o
end