<commit_before>
require 'deltacloud/base_driver'
require 'yaml'

class RHEVMDriver < DeltaCloud::BaseDriver

  SCRIPT_DIR = File.dirname(__FILE__) + '/../scripts'
  SCRIPT_DIR_ARG = '"' + SCRIPT_DIR + '"'
  DELIM_BEGIN="<_OUTPUT>"
  DELIM_END="</_OUTPUT>"
  POWERSHELL="c:\\Windows\\system32\\WindowsPowerShell\\v1.0\\powershell.exe"
  NO_OWNER=""

  #
  # Execute a Powershell command, and convert the output
  # to YAML in order to get back an array of maps.
  #
  def execute(credentials, command, *args)
    args = args.to_a
    argString = genArgString(credentials, args)
    outputMaps = {}
    output = `#{POWERSHELL} -command "&{#{File.join(SCRIPT_DIR, command)} #{argString}; exit $LASTEXITCODE}`
    exitStatus = $?.exitstatus
    puts(output)
    puts("EXITSTATUS #{exitStatus}")
    st = output.index(DELIM_BEGIN)
    if (st)
      st += DELIM_BEGIN.length
      ed = output.index(DELIM_END)
      output = output.slice(st, (ed-st))
      # Lets make it yaml
      output.strip!
      if (output.length > 0)
        outputMaps = YAML.load(self.toYAML(output))
      end
    end
    outputMaps
  end

  def genArgString(credentials, args)
    if ( credentials[:name].nil? || credentials[:password].nil? || credentials[:name] == '' || credentials[:password] == '' )
      raise DeltaCloud::AuthException.new
    end
    commonArgs = [SCRIPT_DIR_ARG, credentials[:name], credentials[:password], "demo"]
    commonArgs.concat(args)
    commonArgs.join(" ")
  end

  def toYAML(output)
    yOutput = "- \n" + output
    yOutput.gsub!(/^(\w*)[ ]*:[ ]*([A-Z0-9a-z._ -:{}]*)/,' \1: "\2"')
    yOutput.gsub!(/^[ ]*$/,"- ")
    puts(yOutput)
    yOutput
  end

  def statify(state)
    st = state.nil? ? "" : state.upcase()
    return "running" if st == "UP"
    return "terminated" if st == "DOWN"
    return "pending" if st == "POWERING UP"
    st
  end

  #
  # Flavors
  #
  FLAVORS = [
    Flavor.new({
      :id=>"rhevm",
      :memory=>"Any Memory",
      :storage=>"Any Storage",
      :architecture=>"Any Architecture",
    })
  ]

  def flavors(credentials, opts=nil)
    return FLAVORS if ( opts.nil? || (! opts[:id]))
    FLAVORS.select{|f| opts[:id] == f.id}
  end


  #
  # Realms
  #

  def realms(credentials, opts=nil)
    domains = execute(credentials, "storageDomains.ps1")
    if (!opts.nil? && opts[:id])
        domains = domains.select{|d| opts[:id] == d["StorageId"]}
    end

    realms = []
    domains.each do |dom|
      realms << domain_to_realm(dom)
    end
    realms
  end

  def domain_to_realm(dom)
    Realm.new({
      :id => dom["StorageId"],
      :name => dom["Name"],
      :limit => dom["AvailableDiskSize"]
    })
  end



  #
  # Images
  #

  def images(credentials, opts=nil )
    templates = []
    if (opts.nil?)
      templates = execute(credentials, "templates.ps1")
    else
      if (opts[:id])
        templates = execute(credentials, "templateById.ps1", opts[:id])
      end
    end
    images = []
    templates.each do |templ|
      images << template_to_image(templ)
    end
    images
  end

  def template_to_image(templ)
    Image.new({
      :id => templ["TemplateId"],
      :name => templ["Name"],
      :description => templ["Description"],
      :architecture => templ["OperatingSystem"],
      :owner_id => NO_OWNER,
      :mem_size_md => templ["MemSizeMb"],
      :instance_count => templ["ChildCount"],
      :state => templ["Status"],
      :capacity => templ["SizeGB"]
    })
  end

  #
  # Instances
  #

  STATE_ACTIONS = [
    [ :pending, {
        :stopped=>:stop,
        :running=>:_auto_ } ],
    [ :running, {
        :running=>:reboot,
        :stopped=>:stop } ],
    [ :shutting_down, {
        :stopped=>:_auto_ } ],
    [ :stopped, {
        :running=>:start,
        :destroyed=>:destroy }],
  ]


  def instance_states()
    STATE_ACTIONS
  end

  def instances(credentials, opts=nil)
    vms = []<commit_msg>Fixed up the state transitions<commit_after>
require 'deltacloud/base_driver'
require 'yaml'

class RHEVMDriver < DeltaCloud::BaseDriver

  SCRIPT_DIR = File.dirname(__FILE__) + '/../scripts'
  SCRIPT_DIR_ARG = '"' + SCRIPT_DIR + '"'
  DELIM_BEGIN="<_OUTPUT>"
  DELIM_END="</_OUTPUT>"
  POWERSHELL="c:\\Windows\\system32\\WindowsPowerShell\\v1.0\\powershell.exe"
  NO_OWNER=""

  #
  # Execute a Powershell command, and convert the output
  # to YAML in order to get back an array of maps.
  #
  def execute(credentials, command, *args)
    args = args.to_a
    argString = genArgString(credentials, args)
    outputMaps = {}
    output = `#{POWERSHELL} -command "&{#{File.join(SCRIPT_DIR, command)} #{argString}; exit $LASTEXITCODE}`
    exitStatus = $?.exitstatus
    puts(output)
    puts("EXITSTATUS #{exitStatus}")
    st = output.index(DELIM_BEGIN)
    if (st)
      st += DELIM_BEGIN.length
      ed = output.index(DELIM_END)
      output = output.slice(st, (ed-st))
      # Lets make it yaml
      output.strip!
      if (output.length > 0)
        outputMaps = YAML.load(self.toYAML(output))
      end
    end
    outputMaps
  end

  def genArgString(credentials, args)
    if ( credentials[:name].nil? || credentials[:password].nil? || credentials[:name] == '' || credentials[:password] == '' )
      raise DeltaCloud::AuthException.new
    end
    commonArgs = [SCRIPT_DIR_ARG, credentials[:name], credentials[:password], "<PASSWORD>"]
    commonArgs.concat(args)
    commonArgs.join(" ")
  end

  def toYAML(output)
    yOutput = "- \n" + output
    yOutput.gsub!(/^(\w*)[ ]*:[ ]*([A-Z0-9a-z._ -:{}]*)/,' \1: "\2"')
    yOutput.gsub!(/^[ ]*$/,"- ")
    puts(yOutput)
    yOutput
  end

  def statify(state)
    st = state.nil? ? "" : state.upcase()
    return "running" if st == "UP"
    return "stopped" if st == "DOWN"
    return "pending" if st == "POWERING UP"
    st
  end

  #
  # Flavors
  #
  FLAVORS = [
    Flavor.new({
      :id=>"rhevm",
      :memory=>"Any Memory",
      :storage=>"Any Storage",
      :architecture=>"Any Architecture",
    })
  ]

  def flavors(credentials, opts=nil)
    return FLAVORS if ( opts.nil? || (! opts[:id]))
    FLAVORS.select{|f| opts[:id] == f.id}
  end


  #
  # Realms
  #

  def realms(credentials, opts=nil)
    domains = execute(credentials, "storageDomains.ps1")
    if (!opts.nil? && opts[:id])
        domains = domains.select{|d| opts[:id] == d["StorageId"]}
    end

    realms = []
    domains.each do |dom|
      realms << domain_to_realm(dom)
    end
    realms
  end

  def domain_to_realm(dom)
    Realm.new({
      :id => dom["StorageId"],
      :name => dom["Name"],
      :limit => dom["AvailableDiskSize"]
    })
  end



  #
  # Images
  #

  def images(credentials, opts=nil )
    templates = []
    if (opts.nil?)
      templates = execute(credentials, "templates.ps1")
    else
      if (opts[:id])
        templates = execute(credentials, "templateById.ps1", opts[:id])
      end
    end
    images = []
    templates.each do |templ|
      images << template_to_image(templ)
    end
    images
  end

  def template_to_image(templ)
    Image.new({
      :id => templ["TemplateId"],
      :name => templ["Name"],
      :description => templ["Description"],
      :architecture => templ["OperatingSystem"],
      :owner_id => NO_OWNER,
      :mem_size_md => templ["MemSizeMb"],
      :instance_count => templ["ChildCount"],
      :state => templ["Status"],
      :capacity => templ["SizeGB"]
    })
  end

  #
  # Instances
  #

  STATE_ACTIONS = [
    [ :pending, {
        :stopped=>:stop,
        :running=>:_auto_ } ],
    [ :running, {
        :running=>:reboot,
        :stopped=>:stop } ],
    [ :shutting_down, {
        :stopped=>:_auto_ } ],
    [ :stopped, {
        :running=>:start,
        :terminated=>:destroy }],
  ]


  def instance_states()
    STATE_ACTIONS
  end

  def instances(credentials, opts=nil)
    vms = []
{'fraction_non_alphanumeric': 0.16463961080527462, 'fraction_numerical': 0.0030725899372679557, 'mean_word_length': 2.725321888412017, 'pattern_counts': {'":': 0, '<': 18, '<?xml version=': 0, '>': 56, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, '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': '2249188', 'n_tokens_mistral': 2839, 'n_tokens_neox': 2742, 'n_words': 536}