Class: DockerfileGenerator

Inherits:
Rails::Generators::Base
  • Object
show all
Includes:
DockerfileRails::Scanner
Defined in:
lib/generators/dockerfile_generator.rb

Constant Summary collapse

BASE_DEFAULTS =
{
  "alpine" => false,
  "bin-cd" => false,
  "cache" => false,
  "ci" => false,
  "compose" => false,
  "fullstaq" => false,
  "gemfile-updates" => true,
  "jemalloc" => false,
  "label" => {},
  "link" => false,
  "litefs" => false,
  "lock" => true,
  "max-idle" => nil,
  "migrate" => "",
  "mysql" => false,
  "nginx" => false,
  "parallel" => false,
  "passenger" => false,
  "platform" => nil,
  "postgresql" => false,
  "precompile" => nil,
  "precompiled-gems" => true,
  "prepare" => true,
  "private-gemserver-domain" => nil,
  "procfile" => "",
  "redis" => false,
  "registry" => "",
  "rollbar" => false,
  "root" => false,
  "sqlite3" => false,
  "sqlserver" => false,
  "sentry" => false,
  "sudo" => false,
  "swap" => nil,
  "tigris" => false,
  "thruster" => false,
  "variant" => nil,
  "windows" => false,
  "yjit" => false,
}.yield_self { |hash| Struct.new(*hash.keys.map(&:to_sym)).new(*hash.values) }
OPTION_DEFAULTS =
BASE_DEFAULTS.dup
ALPINE_MAPPINGS =
{
  "build-essential" => "build-base",
  "chromium-sandbox" => "chromium-chromedriver",
  "default-libmysqlclient-dev" => "mysql-client",
  "default-mysqlclient" => "mysql-client",
  "freedts-bin" => "freedts",
  "libicu-dev" => "icu-dev",
  "libjemalloc" => "jemalloc-dev",
  "libjpeg-dev" => "jpeg-dev",
  "libmagickwand-dev" => "imagemagick-libs",
  "libsqlite3-0" => "sqlite-dev",
  "libtiff-dev" => "tiff-dev",
  "libjemalloc2" => "jemalloc",
  "libvips" => "vips-dev",
  "node-gyp" => "gyp",
  "pkg-config" => "pkgconfig",
  "python" => "python3",
  "python-is-python3" => "python3"
}
@@labels =
options[:label].stringify_keys
@@packages =
{ "base" => [], "build" => [], "deploy" => [] }
@@vars =
{ "base" => {}, "build" => {}, "deploy" => {} }
@@args =
{ "base" => {}, "build" => {}, "deploy" => {} }
@@instructions =
{ "base" => nil, "build" => nil, "deploy" => nil }

Instance Method Summary collapse

Methods included from DockerfileRails::Scanner

#scan_rails_app

Instance Method Details

#generate_appObject



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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
# File 'lib/generators/dockerfile_generator.rb', line 283

def generate_app
  source_paths.push File.expand_path("./templates", __dir__)

  # merge options
  options.label.replace(@@labels.merge(options.label).select { |key, value| value != "" })

  # gather up options for config file
  @dockerfile_config = OPTION_DEFAULTS.dup.to_h.stringify_keys
  options.to_h.each do |option, value|
    @dockerfile_config[option] = value if @dockerfile_config.include? option
  end

  %w(base build deploy).each do |phase|
    @@packages[phase] += options["add-#{phase}"]
    @@packages[phase] -= options["remove-#{phase}"]
    @@packages[phase].uniq!
    @@packages.delete phase if @@packages[phase].empty?

    @@vars[phase].merge! options["env-#{phase}"]
    @@vars[phase].delete_if { |key, value| value.blank? }
    @@vars.delete phase if @@vars[phase].empty?

    @@args[phase].merge! options["arg-#{phase}"]
    @@args[phase].delete_if { |key, value| value.blank? }
    @@args.delete phase if @@args[phase].empty?

    @@instructions[phase] ||= options["instructions-#{phase}"]
    @@instructions.delete phase if @@instructions[phase].empty?
  end

  @dockerfile_config["packages"] = @@packages
  @dockerfile_config["envs"] = @@vars
  @dockerfile_config["args"] = @@args
  @dockerfile_config["instructions"] = @@instructions

  scan_rails_app

  Bundler.with_original_env { install_gems }

  template "Dockerfile.erb", "Dockerfile"
  template "dockerignore.erb", ".dockerignore"

  if using_node? && node_version =~ (/\A\d+\.\d+\.\d+\z/)
    template "node-version.erb", ".node-version"
  end

  template "docker-entrypoint.erb", "bin/docker-entrypoint"
  chmod "bin/docker-entrypoint", 0755 & ~File.umask, verbose: false

  template "docker-compose.yml.erb", "docker-compose.yml" if options.compose

  if fix_database_config
    template "database.yml.erb", "config/database.yml",
      force: options.force? || File.exist?("fly.toml")
  end

  if solidq_launcher == :puma && !File.read("config/puma.rb").include?(":solid_queue")
    append_to_file "config/puma.rb", "\n# Run the Solid Queue's supervisor\nplugin :solid_queue\n"
  end

  if using_litefs?
    template "litefs.yml.erb", "config/litefs.yml"

    fly_attach_consul
  end

  if File.exist?("fly.toml") && (fly_processes || !options.prepare || options.swap || deploy_database == "sqlite3")
    if File.stat("fly.toml").size > 0
      template "fly.toml.erb", "fly.toml"
    else
      toml = fly_make_toml
      File.write "fly.toml", toml if toml != ""
    end
  end

  if options.sentry? && (not File.exist?("config/initializers/sentry.rb"))
    template "sentry.rb.erb", "config/initializers/sentry.rb"
  end

  if options.rollbar? && (not File.exist?("config/initializers/rollbar.rb"))
    template "rollbar.rb.erb", "config/initializers/rollbar.rb"
  end

  if @gemfile.include?("vite_ruby")
    package = JSON.load_file("package.json")
    unless package.dig("scripts", "build")
      package["scripts"] ||= {}
      package["scripts"]["build"] = "vite build --outDir public"

      say_status :update, "package.json"
      IO.write("package.json", JSON.pretty_generate(package))
    end
  end

  @dockerfile_config = (@dockerfile_config.to_a - BASE_DEFAULTS.to_h.stringify_keys.to_a).to_h
  %w(packages envs args instructions).each do |key|
    @dockerfile_config.delete key if @dockerfile_config[key].empty?
  end

  if !@dockerfile_config.empty?
    template "dockerfile.yml.erb", "config/dockerfile.yml", force: true
  elsif File.exist? "config/dockerfile.yml"
    remove_file "config/dockerfile.yml"
  end

  if options.tigris?
    configure_tigris
  end

  # check Dockerfile for common errors: missing packages, mismatched Ruby version;
  # also add DATABASE_URL to fly.toml if needed
  if options.skip? && File.exist?("Dockerfile")
    message = nil
    shell = Thor::Base.shell.new

    dockerfile = IO.read("Dockerfile")
    missing = Set.new(base_packages + build_packages) -
      Set.new(dockerfile.scan(/[-\w]+/))

    unless missing.empty?
      message = "The following packages are missing from the Dockerfile: #{missing.to_a.join(", ")}"
      STDERR.puts "\n" + shell.set_color(message, Thor::Shell::Color::RED, Thor::Shell::Color::BOLD)
    end

    ruby_version = dockerfile.match(/ARG RUBY_VERSION=(\d+\.\d+\.\d+)/)[1]

    if ruby_version && ruby_version != RUBY_VERSION
      message = "The Ruby version in the Dockerfile (#{ruby_version}) does not match the Ruby version of the Rails app (#{RUBY_VERSION})"
      STDERR.puts "\n" + shell.set_color(message, Thor::Shell::Color::RED, Thor::Shell::Color::BOLD)
    end

    if @netpopbug && !dockerfile.include?("net-pop")
      message = "Ruby 3.3.3 net-pop bug detected."
      STDERR.puts "\n" + shell.set_color(message, Thor::Shell::Color::RED, Thor::Shell::Color::BOLD)
      STDERR.puts "Please see https://github.com/ruby/ruby/pull/11006"
      STDERR.puts "Change your Ruby version, or run `bin/rails generate dockerfile`,"
      STDERR.puts "or add the following to your Dockerfile:"
      STDERR.puts 'RUN sed -i "/net-pop (0.1.2)/a\      net-protocol" Gemfile.lock'
    end

    if File.exist?("fly.toml")
      env = fly_toml_env

      unless env.empty?
        toml = IO.read("fly.toml")
        if !toml.include?("[env]")
          toml += "\n[env]\n" + env.map { |key, value| "  #{key} = #{value.inspect}" }.join("\n") + "\n"
          File.write "fly.toml", toml
        end
      end
    end

    exit 42 if message
  end
end