Class: BoxGrinder::RPMBasedOSPlugin

Inherits:
BasePlugin show all
Defined in:
lib/boxgrinder-build/plugins/os/rpm-based/rpm-based-os-plugin.rb

Direct Known Subclasses

FedoraPlugin, RHELPlugin

Instance Attribute Summary

Attributes inherited from BasePlugin

#deliverables, #plugin_info

Instance Method Summary collapse

Methods inherited from BasePlugin

#current_platform, #deliverables_exists?, #execute, #init, #initialize, #is_supported_os?, #is_supported_platform?, #merge_plugin_config, #read_plugin_config, #register_deliverable, #register_supported_os, #register_supported_platform, #run, #set_default_config_value, #subtype, #supported_oses, #validate_plugin_config

Methods included from Plugins

#plugin

Constructor Details

This class inherits a constructor from BoxGrinder::BasePlugin

Instance Method Details

#add_repos(repos) ⇒ Object

Add default repos (if present) to the list of additional repositories specified in appliance definition.



40
41
42
43
44
45
46
47
48
49
50
# File 'lib/boxgrinder-build/plugins/os/rpm-based/rpm-based-os-plugin.rb', line 40

def add_repos(repos)
  return if repos.empty?

  repos[@appliance_config.os.version].each do |name, repo|
    r = { 'name' => name, 'ephemeral' => true }

    ['baseurl', 'mirrorlist'].each { |type| r[type] = substitute_vars(repo[type]) unless repo[type].nil? }

    @appliance_config.repos << r
  end
end

#after_initObject



28
29
30
31
32
33
34
35
36
37
# File 'lib/boxgrinder-build/plugins/os/rpm-based/rpm-based-os-plugin.rb', line 28

def after_init
  set_default_config_value('format', 'raw')

  register_deliverable(
      :disk => "#{@appliance_config.name}-sda.#{@plugin_config['format']}",
      :descriptor => "#{@appliance_config.name}.xml"
  )

  @linux_helper = LinuxHelper.new(:log => @log)
end

#apply_root_password(guestfs) ⇒ Object



221
222
223
224
225
226
# File 'lib/boxgrinder-build/plugins/os/rpm-based/rpm-based-os-plugin.rb', line 221

def apply_root_password(guestfs)
  @log.debug "Applying root password..."
  guestfs.sh("/usr/bin/passwd -d root")
  guestfs.sh("/usr/sbin/usermod -p '#{@appliance_config.os.password.crypt((0...8).map { 65.+(rand(25)).chr }.join)}' root")
  @log.debug "Password applied."
end

#build_with_appliance_creator(appliance_definition_file, repos = {}) ⇒ Object



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
# File 'lib/boxgrinder-build/plugins/os/rpm-based/rpm-based-os-plugin.rb', line 61

def build_with_appliance_creator(appliance_definition_file, repos = {})
  @appliance_definition_file = appliance_definition_file

  add_repos(repos) if @appliance_config.default_repos

  kickstart_file = Kickstart.new(@config, @appliance_config, @dir, :log => @log).create
  RPMDependencyValidator.new(@config, @appliance_config, @dir, :log => @log).resolve_packages

  @log.info "Building #{@appliance_config.name} appliance..."

  execute_appliance_creator(kickstart_file)

  FileUtils.mv(Dir.glob("#{@dir.tmp}/#{@appliance_config.name}/*"), @dir.tmp)
  FileUtils.rm_rf("#{@dir.tmp}/#{@appliance_config.name}/")

  @image_helper.customize([@deliverables.disk]) do |guestfs, guestfs_helper|
    # TODO is this really needed?
    @log.debug "Uploading '/etc/resolv.conf'..."
    guestfs.upload("/etc/resolv.conf", "/etc/resolv.conf")
    @log.debug "'/etc/resolv.conf' uploaded."

    change_configuration(guestfs_helper)
    # TODO check if this is still required
    apply_root_password(guestfs)
    set_label_for_swap_partitions(guestfs, guestfs_helper)
    use_labels_for_partitions(guestfs)
    disable_firewall(guestfs)
    set_motd(guestfs)
    install_repos(guestfs)
    install_files(guestfs)

    guestfs.sh("chkconfig firstboot off") if guestfs.exists('/etc/init.d/firstboot') != 0

    # https://issues.jboss.org/browse/BGBUILD-148
    recreate_rpm_database(guestfs, guestfs_helper) if @config.os.name != @appliance_config.os.name or @config.os.version != @appliance_config.os.version

    execute_post(guestfs_helper)

    yield guestfs, guestfs_helper if block_given?
  end

  @log.info "Base image for #{@appliance_config.name} appliance was built successfully."
end

#change_configuration(guestfs_helper) ⇒ Object



228
229
230
231
232
233
# File 'lib/boxgrinder-build/plugins/os/rpm-based/rpm-based-os-plugin.rb', line 228

def change_configuration(guestfs_helper)
  guestfs_helper.augeas do
    set('/etc/ssh/sshd_config', 'UseDNS', 'no')
    set('/etc/sysconfig/selinux', 'SELINUX', 'permissive')
  end
end

#cleanup_after_appliance_creator(pid) ⇒ Object



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
# File 'lib/boxgrinder-build/plugins/os/rpm-based/rpm-based-os-plugin.rb', line 140

def cleanup_after_appliance_creator(pid)
  @log.debug "Sending TERM signal to process '#{pid}'..."
  Process.kill("TERM", pid)

  @log.debug "Waiting for process to be terminated..."
  Process.wait(pid)

  @log.debug "Cleaning appliance-creator mount points..."

  Dir["#{@dir.tmp}/imgcreate-*"].each do |dir|
    dev_mapper = @exec_helper.execute("mount | grep #{dir} | awk '{print $1}'").split("\n")

    mappings = {}

    dev_mapper.each do |mapping|
      if mapping =~ /(loop\d+)p(\d+)/
        mappings[$1] = [] if mappings[$1].nil?
        mappings[$1] << $2 unless mappings[$1].include?($2)
      end
    end

    (['/var/cache/yum', '/dev/shm', '/dev/pts', '/proc', '/sys'] + @appliance_config.hardware.partitions.keys.sort.reverse).each do |mount_point|
      @log.trace "Unmounting '#{mount_point}'..."
      @exec_helper.execute "umount -d #{dir}/install_root#{mount_point}"
    end

    mappings.each do |loop, partitions|
      @log.trace "Removing mappings from loop device #{loop}..."
      @exec_helper.execute "/sbin/kpartx -d /dev/#{loop}"
      @exec_helper.execute "losetup -d /dev/#{loop}"

      partitions.each do |part|
        @log.trace "Removing mapping for partition #{part} from loop device #{loop}..."
        @exec_helper.execute "rm /dev/#{loop}#{part}"
      end
    end
  end

  @log.debug "Cleaned up after appliance-creator."
end

#disable_firewall(guestfs) ⇒ Object



182
183
184
185
186
# File 'lib/boxgrinder-build/plugins/os/rpm-based/rpm-based-os-plugin.rb', line 182

def disable_firewall(guestfs)
  @log.debug "Disabling firewall..."
  guestfs.sh("lokkit -q --disabled")
  @log.debug "Firewall disabled."
end

#execute_appliance_creator(kickstart_file) ⇒ Object



105
106
107
108
109
110
111
112
# File 'lib/boxgrinder-build/plugins/os/rpm-based/rpm-based-os-plugin.rb', line 105

def execute_appliance_creator(kickstart_file)
  begin
    @exec_helper.execute "appliance-creator -d -v -t '#{@dir.tmp}' --cache=#{@config.dir.cache}/rpms-cache/#{@appliance_config.path.main} --config '#{kickstart_file}' -o '#{@dir.tmp}' --name '#{@appliance_config.name}' --vmem #{@appliance_config.hardware.memory} --vcpu #{@appliance_config.hardware.cpus} --format #{@plugin_config['format']}"
  rescue InterruptionError => e
    cleanup_after_appliance_creator(e.pid)
    abort
  end
end

#execute_post(guestfs_helper) ⇒ Object



114
115
116
117
118
119
120
121
122
123
124
# File 'lib/boxgrinder-build/plugins/os/rpm-based/rpm-based-os-plugin.rb', line 114

def execute_post(guestfs_helper)
  @log.info "Executing post operations after build..."
  unless @appliance_config.post['base'].nil?
    @appliance_config.post['base'].each do |cmd|
      guestfs_helper.sh(cmd, :arch => @appliance_config.hardware.arch)
    end
    @log.debug "Post commands from appliance definition file executed."
  else
    @log.debug "No commands specified, skipping."
  end
end

#install_files(guestfs) ⇒ Object

Copies specified files into appliance.

There are two types of paths:

  1. remote - starting with http:// or https:// or ftp://
  2. local - all other.

Please use relative paths. Relative means relative to the appliance definition file. Using absolute paths will cause creating whole directory structure in appliance, which is most probably not exactly what you want.

https://issues.jboss.org/browse/BGBUILD-276



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
325
326
327
328
329
330
331
# File 'lib/boxgrinder-build/plugins/os/rpm-based/rpm-based-os-plugin.rb', line 288

def install_files(guestfs)
  @log.debug "Installing files specified in appliance definition file..."

  @appliance_config.files.each do |dir, files|

    @log.debug "Proceding files for '#{dir}' destination directory..."

    local_files = []

    # Create the directory if it doesn't exists
    guestfs.mkdir_p(dir) unless guestfs.exists(dir) != 0

    files.each do |f|
      if f.match(/^(http|ftp|https):\/\//)
        # Remote url provided
        @log.trace "Remote url detected: '#{f}'."

        # We have a remote file, try to download it using curl!
        guestfs.sh("cd #{dir} && curl -O -L #{f}")
      else
        @log.trace "Local path detected: '#{f}'."

        file_path = (f.match(/^\//) ? f : "#{File.dirname(@appliance_definition_file)}/#{f}")

        # TODO validate this earlier
        raise ValidationError, "File '#{f}' specified in files section of appliance definition file doesn't exists." unless File.exists?(file_path)

        local_files << f
      end
    end

    next if local_files.empty?

    @log.trace "Tarring files..."
    @exec_helper.execute("cd #{File.dirname(@appliance_definition_file)} && tar -cvf /tmp/bg_install_files.tar --wildcards #{local_files.join(' ')}")
    @log.trace "Files tarred."

    @log.trace "Uploading and unpacking..."
    guestfs.tar_in("/tmp/bg_install_files.tar", dir)
    @log.trace "Files uploaded."

  end
  @log.debug "Files installed."
end

#install_repos(guestfs) ⇒ Object



252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
# File 'lib/boxgrinder-build/plugins/os/rpm-based/rpm-based-os-plugin.rb', line 252

def install_repos(guestfs)
  @log.debug "Installing repositories from appliance definition file..."

  # It seems that the directory is not always created by default if default repos are inhibited (e.g. SL6)
  yum_d = '/etc/yum.repos.d/'
  guestfs.mkdir_p(yum_d) if guestfs.exists(yum_d) == 0

  @appliance_config.repos.each do |repo|
    if repo['ephemeral']
      @log.debug "Repository '#{repo['name']}' is an ephemeral repo. It'll not be installed in the appliance."
      next
    end

    @log.debug "Installing #{repo['name']} repo..."
    repo_file = File.read("#{File.dirname(__FILE__)}/src/base.repo").gsub(/#NAME#/, repo['name'])

    ['baseurl', 'mirrorlist'].each do |type|
      repo_file << ("#{type}=#{repo[type]}\n") unless repo[type].nil?
    end

    guestfs.write_file("#{yum_d}#{repo['name']}.repo", repo_file, 0)
  end
  @log.debug "Repositories installed."
end

#recreate_kernel_image(guestfs, modules = []) ⇒ Object



248
249
250
# File 'lib/boxgrinder-build/plugins/os/rpm-based/rpm-based-os-plugin.rb', line 248

def recreate_kernel_image(guestfs, modules = [])
  @linux_helper.recreate_kernel_image(guestfs, modules)
end

#recreate_rpm_database(guestfs, guestfs_helper) ⇒ Object



127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/boxgrinder-build/plugins/os/rpm-based/rpm-based-os-plugin.rb', line 127

def recreate_rpm_database(guestfs, guestfs_helper)
  @log.debug "Recreating RPM database..."

  guestfs.download("/var/lib/rpm/Packages", "#{@dir.tmp}/Packages")
  @exec_helper.execute("/usr/lib/rpm/rpmdb_dump #{@dir.tmp}/Packages > #{@dir.tmp}/Packages.dump")
  guestfs.upload("#{@dir.tmp}/Packages.dump", "/tmp/Packages.dump")
  guestfs.sh("rm -rf /var/lib/rpm/*")
  guestfs_helper.sh("cd /var/lib/rpm/ && cat /tmp/Packages.dump | /usr/lib/rpm/rpmdb_load Packages")
  guestfs_helper.sh("rpm --rebuilddb")

  @log.debug "RPM database recreated..."
end

#set_label_for_swap_partitions(guestfs, guestfs_helper) ⇒ Object



189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'lib/boxgrinder-build/plugins/os/rpm-based/rpm-based-os-plugin.rb', line 189

def set_label_for_swap_partitions(guestfs, guestfs_helper)
  @log.trace "Searching for swap partition to set label..."

  guestfs_helper.mountable_partitions(guestfs.list_devices.first, :list_swap => true).each do |p|
    if guestfs.vfs_type(p).eql?('swap')
      @log.debug "Setting 'swap' label for partiiton '#{p}'."
      guestfs.mkswap_L('swap', p)
      @log.debug "Label set."
      # We assume here that nobody will want to have two swap partitions
      break
    end
  end
end

#set_motd(guestfs) ⇒ Object



235
236
237
238
239
240
241
242
243
244
245
246
# File 'lib/boxgrinder-build/plugins/os/rpm-based/rpm-based-os-plugin.rb', line 235

def set_motd(guestfs)
  @log.debug "Setting up '/etc/motd'..."
  # set nice banner for SSH
  motd_file = "/etc/init.d/motd"
  guestfs.upload("#{File.dirname(__FILE__)}/src/motd.init", motd_file)
  guestfs.sh("sed -i s/#VERSION#/'#{@appliance_config.version}.#{@appliance_config.release}'/ #{motd_file}")
  guestfs.sh("sed -i s/#APPLIANCE#/'#{@appliance_config.name} appliance'/ #{motd_file}")

  guestfs.sh("/bin/chmod +x #{motd_file}")
  guestfs.sh("/sbin/chkconfig --add motd")
  @log.debug "'/etc/motd' is nice now."
end

#substitute_vars(str) ⇒ Object

Substitute variables in selected string.



53
54
55
56
57
58
59
# File 'lib/boxgrinder-build/plugins/os/rpm-based/rpm-based-os-plugin.rb', line 53

def substitute_vars(str)
  return if str.nil?
  @appliance_config.variables.keys.each do |var|
    str = str.gsub("##{var}#", @appliance_config.variables[var])
  end
  str
end

#use_labels_for_partitions(guestfs) ⇒ Object



203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
# File 'lib/boxgrinder-build/plugins/os/rpm-based/rpm-based-os-plugin.rb', line 203

def use_labels_for_partitions(guestfs)
  @log.debug "Using labels for partitions..."
  device = guestfs.list_devices.first

  # /etc/fstab
  if fstab = guestfs.read_file('/etc/fstab').gsub!(%r(^(/dev/\w+da\d*))) { |path| "LABEL=#{guestfs.vfs_label(path.gsub('/dev/sda', device))}" }
    guestfs.write_file('/etc/fstab', fstab, 0)
  end

  # /boot/grub/grub.conf
  if guestfs.exists('/boot/grub/grub.conf') != 0
    if grub = guestfs.read_file('/boot/grub/grub.conf').gsub!(%r((/dev/\w+da\d*))) { |path| "LABEL=#{guestfs.vfs_label(path.gsub('/dev/sda', device))}" }
      guestfs.write_file('/boot/grub/grub.conf', grub, 0)
    end
  end
  @log.debug "Done."
end