<commit_before>require 'active_record'
require 'active_support/core_ext'
require 'linux_admin'
require 'pathname'
require 'util/miq-password'
require 'fileutils'
require 'appliance_console/errors'
require 'appliance_console/utilities'
require 'appliance_console/logging'

RAILS_ROOT ||= Pathname.new(__dir__).join("../../..")

module ApplianceConsole
  class DatabaseConfiguration
    attr_accessor :adapter, :host, :username, :database, :password, :port, :region

    class ModelWithNoBackingTable < ActiveRecord::Base
    end

    DB_YML      = RAILS_ROOT.join("config/database.yml")
    DB_YML_TMPL = RAILS_ROOT.join("config/database.pg.yml")

    CREATE_REGION_AGREE = "WARNING: Creating a database region will destroy any existing data and cannot be undone.\n\nAre you sure you want to continue? (Y/N):".freeze
    FAILED_WITH_ERROR_HYPHEN = "failed with error -".freeze

    # PG 9.2 bigint max 9223372036854775807 / ArRegion::DEFAULT_RAILS_SEQUENCE_FACTOR = 9223372
    # http://www.postgresql.org/docs/9.2/static/datatype-numeric.html
    # 9223372 won't be a full region though, so we're not including it.
    # TODO: This information should be shared outside of appliance console code and MiqRegion.
    REGION_RANGE = 0..9223371

    include ApplianceConsole::Logging

    def initialize(hash = {})
      initialize_from_hash(hash)
      @adapter ||= "postgresql"
      # introduced by Logging
      self.interactive = true unless hash.key?(:interactive)
    end

    def local?
      host.blank? || host.in?(%w(localhost 127.0.0.1))
    end

    def password=(value)
      @password = <PASSWORD>(value)
    end

    def activate
      return false unless validated

      original = self.class.current
      success  = false

      begin
        save
        success = create_or_join_region
      rescue
        success = false
      ensure
        save(original) unless success
      end
    end

    def post_activation
      ServiceGroup.new.restart_services
      LinuxAdmin::Service.new("evmserverd").enable.start
    end

    def create_or_join_region
      region ? create_region : join_region
    end

    def create_region
      log_and_feedback(__method__) do
        AwesomeSpawn.run!(
          "script/rails runner script/rake",
          :params => ["evm:db:region", "--", {:region => region}],
          :chdir  => RAILS_ROOT
        )
      end
    end

    def join_region
      require 'tempfile'
      temp = Tempfile.new(["joinregion", ".rb"], RAILS_ROOT.join("tmp").to_s)
      params = {nil => ['runner', temp.path]}

      output = nil

      begin
        temp.write(activation_code)
        temp.close

        output = LinuxAdmin.run('script/rails', :chdir => RAILS_ROOT, :params => params).output
      ensure
        temp.delete
      end

      if output.to_s.empty?
        true
      else
        say("\n#{output}") if interactive?
        false<commit_msg>use utils.rake for region creation<commit_after>require 'active_record'
require 'active_support/core_ext'
require 'linux_admin'
require 'pathname'
require 'util/miq-password'
require 'fileutils'
require 'appliance_console/errors'
require 'appliance_console/utilities'
require 'appliance_console/logging'

RAILS_ROOT ||= Pathname.new(__dir__).join("../../..")

module ApplianceConsole
  class DatabaseConfiguration
    attr_accessor :adapter, :host, :username, :database, :password, :port, :region

    class ModelWithNoBackingTable < ActiveRecord::Base
    end

    DB_YML      = RAILS_ROOT.join("config/database.yml")
    DB_YML_TMPL = RAILS_ROOT.join("config/database.pg.yml")

    CREATE_REGION_AGREE = "WARNING: Creating a database region will destroy any existing data and cannot be undone.\n\nAre you sure you want to continue? (Y/N):".freeze
    FAILED_WITH_ERROR_HYPHEN = "failed with error -".freeze

    # PG 9.2 bigint max 9223372036854775807 / ArRegion::DEFAULT_RAILS_SEQUENCE_FACTOR = 9223372
    # http://www.postgresql.org/docs/9.2/static/datatype-numeric.html
    # 9223372 won't be a full region though, so we're not including it.
    # TODO: This information should be shared outside of appliance console code and MiqRegion.
    REGION_RANGE = 0..9223371

    include ApplianceConsole::Logging

    def initialize(hash = {})
      initialize_from_hash(hash)
      @adapter ||= "postgresql"
      # introduced by Logging
      self.interactive = true unless hash.key?(:interactive)
    end

    def local?
      host.blank? || host.in?(%w(localhost 127.0.0.1))
    end

    def password=(value)
      @password = <PASSWORD>(value)
    end

    def activate
      return false unless validated

      original = self.class.current
      success  = false

      begin
        save
        success = create_or_join_region
      rescue
        success = false
      ensure
        save(original) unless success
      end
    end

    def post_activation
      ServiceGroup.new.restart_services
      LinuxAdmin::Service.new("evmserverd").enable.start
    end

    def create_or_join_region
      region ? create_region : join_region
    end

    def create_region
      log_and_feedback(__method__) do
        ApplianceConsole::Utilities.rake("evm:db:region", ["--", {:region => region}])
      end
    end

    def join_region
      require 'tempfile'
      temp = Tempfile.new(["joinregion", ".rb"], RAILS_ROOT.join("tmp").to_s)
      params = {nil => ['runner', temp.path]}

      output = nil

      begin
        temp.write(activation_code)
        temp.close

        output = LinuxAdmin.run('script/rails', :chdir => RAILS_ROOT, :params => params).output
      ensure
        temp.delete
      end

      if output.to_s.empty?
        true
      else
        say("\n#{output}") if interactive?
        false
{'fraction_non_alphanumeric': 0.10162388685175484, 'fraction_numerical': 0.0178103719224725, 'mean_word_length': 2.8468770987239758, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 2, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5934462', 'n_tokens_mistral': 1853, 'n_tokens_neox': 1729, 'n_words': 422}