You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@deltacloud.apache.org by mf...@redhat.com on 2010/12/20 17:41:24 UTC

[PATCH core 2/2] Fixed a lot bugs inside RHEV driver Added support for creating VMs

From: Michal Fojtik <mf...@redhat.com>

---
 .../lib/deltacloud/drivers/rhevm2/rhevm2_driver.rb |   75 ++++++++++++++------
 .../lib/deltacloud/drivers/rhevm2/rhevm_client.rb  |   66 +++++++++++-------
 2 files changed, 94 insertions(+), 47 deletions(-)

diff --git a/server/lib/deltacloud/drivers/rhevm2/rhevm2_driver.rb b/server/lib/deltacloud/drivers/rhevm2/rhevm2_driver.rb
index f1655d1..25b3345 100644
--- a/server/lib/deltacloud/drivers/rhevm2/rhevm2_driver.rb
+++ b/server/lib/deltacloud/drivers/rhevm2/rhevm2_driver.rb
@@ -36,13 +36,13 @@ class RHEVM2Driver < Deltacloud::BaseDriver
 
   define_hardware_profile 'SERVER' do
     cpu         1
-    memory      [ 1*1024 .. 32*1024 ]
+    memory      ( 512 .. 32*1024 )
     architecture 'x86_64'
   end
 
   define_hardware_profile 'DESKTOP' do
     cpu         1
-    memory      [ 1*1024 .. 32*1024 ]
+    memory      ( 512 .. 32*1024 )
     architecture 'x86_64'
   end
 
@@ -55,7 +55,7 @@ class RHEVM2Driver < Deltacloud::BaseDriver
 
   def provider_uri
     # 'http://localhost:8099/rhevm-api-mock/' || @RHEVM_URI
-    'http://localhost:8080'
+    'https://10.34.2.122:8443/rhevm-api-powershell'
   end
 
   # FIX: This is state table from EC2, fix it pls to 
@@ -64,9 +64,10 @@ class RHEVM2Driver < Deltacloud::BaseDriver
   define_instance_states do
     start.to( :pending )          .automatically
     pending.to( :running )        .automatically
-    pending.to( :stopping )       .on( :stop )
     pending.to( :stopped )        .automatically
+    pending.to( :finish )         .on(:destroy)
     stopped.to( :running )        .on( :start )
+    stopped.to( :finish )         .on( :destroy )
     running.to( :running )        .on( :reboot )
     running.to( :stopping )       .on( :stop )
     shutting_down.to( :stopped )  .automatically
@@ -98,7 +99,7 @@ class RHEVM2Driver < Deltacloud::BaseDriver
         templates = templates.select{|t| opts[:id] == t.id}
       end
       templates.each do |t|
-        img_arr << convert_image(t)
+        img_arr << convert_image(client, t)
       end
     end
     img_arr = filter_on( img_arr, :architecture, opts )
@@ -125,6 +126,13 @@ class RHEVM2Driver < Deltacloud::BaseDriver
     end
   end
 
+  def start_instance(credentials, id)
+    client = new_client(credentials)
+    safely do
+      client.vm_action(:start, id)
+    end
+  end
+
   def stop_instance(credentials, id)
     client = new_client(credentials)
     safely do
@@ -132,17 +140,30 @@ class RHEVM2Driver < Deltacloud::BaseDriver
     end
   end
 
-  def start_instance(credentials, id)
+  def destroy_instance(credentials, id)
     client = new_client(credentials)
     safely do
-      client.vm_action(:start, id)
+      client.delete_vm(id)
     end
   end
 
-  def shutdown_instance(credentials, id)
+  def create_instance(credentials, image_id, opts={})
     client = new_client(credentials)
     safely do
-      client.vm_action(:shutdown, id)
+      cluster = get_cluster_from_realm(client, opts[:realm_id] || 'Default')
+      vm_name = opts[:name] ? "<name>#{opts[:name]}</name>" : ""
+      vm_template = "<template id='#{image_id}'/>"
+      vm_cluster = opts[:realm_id] ? "<cluster id='#{cluster.id}'/>" : "<cluster id='Default'/>"
+      # This cause Internal Server Error on RHEV-API side
+      # vm_memory = opts[:hwp_memory] ? "<memory>#{opts[:hwp_memory].to_i*1024}</memory>"  : ''
+      convert_instance(client, RHEVM::Vm::new(client, client.create_vm(
+        "<vm>"+
+        vm_name +
+        vm_template +
+        vm_cluster +
+        # vm_memory +
+        "</vm>"
+      ).xpath('vm')))
     end
   end
 
@@ -153,10 +174,15 @@ class RHEVM2Driver < Deltacloud::BaseDriver
     RHEVM::Client.new(credentials.user, credentials.password, provider_uri, opts)
   end
 
+  def get_cluster_from_realm(client, datacenter_id)
+    clusters = client.clusters
+    clusters.select { |c| c.datacenter_id }.first
+  end
+
   # I can't test this method, since 'cluster' is not a part of Mock driver
   def get_realm_from_cluster(client, cluster_id)
     cluster = client.clusters(:id => cluster_id)
-    datacenter = client.datacenter(:id => cluster.datacenter_id)
+    datacenter = client.datacenters(:id => cluster.datacenter_id)
     convert_realm(datacenter)
   end
 
@@ -164,18 +190,16 @@ class RHEVM2Driver < Deltacloud::BaseDriver
     # FIXME: Remove 'DOWN', it's used just because RHEV Mock driver
     #        has no 'state' property in XML.
     #
-    # FIXME2: This call will now throw 500 because I'm unable to fetch realm
-    # for instance. 
-    #
     state = convert_state(inst.status=='' ? 'DOWN' : inst.status)
+    instance_realm = get_realm_from_cluster(client, inst.cluster)
     Instance.new(
       :id => inst.id,
       :name => inst.name,
       :state => state,
       :image_id => inst.template,
       # Realm aka DataCenter could be retrieved from Cluster
-      :realm_id => get_realm_from_cluster(client, inst.cluster),
-      :owner_id => 'self',
+      :realm_id => instance_realm ? instance_realm.id : nil,
+      :owner_id => client.username,
       :launch_time => inst.creation_time,
       :instance_profile => InstanceProfile::new(inst.profile),
       :hardware_profile_id => inst.profile,
@@ -192,37 +216,44 @@ class RHEVM2Driver < Deltacloud::BaseDriver
   # FIXME: This will need to be fixed regarding to state-machine
   def convert_state(state)
     case state
-    when 'POWERING_UP', 'WAIT_FOR_LAUNCH', 'REBOOT_IN_PROGRESS', 'SAVING_STATE',
+    when 'WAIT_FOR_LAUNCH', 'REBOOT_IN_PROGRESS', 'SAVING_STATE',
       'RESTORING_STATE', 'POWERING_DOWN' then
       'PENDING'
     when 'UNASSIGNED', 'DOWN', 'POWERING_DOWN', 'PAUSED', 'NOT_RESPONDING', 'SAVING_STATE', 
       'SUSPENDED', 'IMAGE_ILLEGAL', 'IMAGE_LOCKED', 'UNKNOWN' then
       'STOPPED'
-    when 'UP', 'MIGRATING_TO', 'MIGRATING_FROM'
+    when 'POWERING_UP', 'UP', 'MIGRATING_TO', 'MIGRATING_FROM'
       'RUNNING'
     end
   end
 
-  def convert_image(img)
+  def convert_image(client, img)
     Image.new(
       :id => img.id,
       :name => img.name,
       :description => img.description,
-      :owner_id => 'self',
+      :owner_id => client.username,
       :architecture => 'x86_64', # All RHEV-M VMs are x86_64
       :status => img.status
     )
   end
 
-  def convert_realm(realm)
+  def convert_realm(dc)
     Realm.new(
-      :id => realm.id,
-      :name => realm.name,
+      :id => dc.id,
+      :name => dc.name,
       :state => 'AVAILABLE',
       :limit => :unlimited
     )
   end
 
+#  def catched_exceptions_list
+#    {
+#      :auth => RestClient::Unauthorized,
+#      :error => RestClient::InternalServerError,
+#      :glob => [ /RestClient::(\w+)/ ]
+#    }
+#  end
 
 end
 
diff --git a/server/lib/deltacloud/drivers/rhevm2/rhevm_client.rb b/server/lib/deltacloud/drivers/rhevm2/rhevm_client.rb
index 856844c..25d886a 100644
--- a/server/lib/deltacloud/drivers/rhevm2/rhevm_client.rb
+++ b/server/lib/deltacloud/drivers/rhevm2/rhevm_client.rb
@@ -1,9 +1,4 @@
-require 'rubygems'
-
-#gem 'rest-client'
-
 require 'base64'
-require 'logger'
 require 'restclient'
 require 'nokogiri'
 
@@ -11,17 +6,18 @@ module RHEVM
 
   class Client
     attr_reader :base_uri
+    attr_reader :host
     attr_reader :entry_points
-    attr_reader :logger
+    attr_reader :username
 
     # Define a list of supported collections which will be handled automatically
     # by method_missing
     @@COLLECTIONS = [ :templates, :clusters, :storagedomains, :vms, :datacenters ]
 
     def initialize(username, password, base_uri, opts={})
-      @logger = opts[:verbose] ? Logger.new(STDERR) : []
       @username, @password = username, password
-      URI.parse(base_uri)
+      uri = URI.parse(base_uri)
+      @host = "#{uri.scheme}://#{uri.host}:#{uri.port}"
       @base_uri = base_uri
       @entry_points = {}
       discover_entry_points()
@@ -30,14 +26,14 @@ module RHEVM
     def method_missing(method_name, *args)
       opts = args[0] if args[0].class.eql?(Hash)
       opts ||= {}
-      puts opts.inspect
       if @@COLLECTIONS.include?(method_name.to_sym)
         if opts[:id]
-          object = Nokogiri::XML(get("%s/%s" % @entry_points[method_name.to_s], opts[:id]))
+          puts "[GET] #{@entry_points[method_name.to_s]}#{opts[:id]}"
+          object = Nokogiri::XML(get("#{@entry_points[method_name.to_s]}#{opts[:id]}"))
           element = method_name.to_s
           element = 'data_centers' if method_name.eql?(:datacenters)
+          puts ">>>> #{element}"
           inst = RHEVM.const_get(element.classify)
-          puts inst.inspect
           return inst::new(self, object)
         else
           objects = Nokogiri::XML(get(@entry_points[method_name.to_s]))
@@ -57,34 +53,55 @@ module RHEVM
     end
 
     def vm_action(action, vm)
-      Nokogiri::XML(post("/vms/%s/" % action.to_s))
+      response = post("#{@base_uri}/vms/#{vm}/%s" % action)
+      Nokogiri::XML(response)
+    end
+
+    def create_vm(opts="")
+      Nokogiri::XML(post("#{@base_uri}/vms", opts))
+    end
+
+    def delete_vm(id)
+      delete("#{@base_uri}/vms/#{id}")
     end
 
     protected
 
+    def delete(uri)
+      headers = {
+        :authorization => "Basic " + Base64.encode64("#{@username}:#{@password}"),
+        :accept => 'application/xml',
+      }
+      RestClient.delete(uri, headers).to_s
+    end
+
     def get(uri)
       headers = {
         :authorization => "Basic " + Base64.encode64("#{@username}:#{@password}"),
-        :accept => "application/xml"
+        :accept => 'application/xml',
       }
-      @logger << "GET #{uri}\n"
-      RestClient.get(uri, headers).to_s()
+      response = RestClient.get(uri, headers).to_s
+      puts "=====\n#{response}\n====="
+      response
     end
 
-    def post(uri, params={})
+    def post(uri, params="")
       headers = {
         :authorization => "Basic " + Base64.encode64("#{@username}:#{@password}"),
-        :accept => "application/xml"
+        :accept => 'application/xml',
+        :content_type => 'application/xml'
       }
-      @logger << "POST #{uri}\n"
-      RestClient.post(uri, params, headers).to_s
+      params = "<action/>" if params.size==0
+      response = RestClient.post(uri, params, headers).to_s
+      puts "=====\n#{response}\n====="
+      response
     end
 
     def discover_entry_points()
       return if @discovered
       doc = Nokogiri.XML(get(@base_uri))
       doc.xpath('api/link').each() do |link|
-        @entry_points[link['rel']] = @base_uri + link['href']
+        @entry_points[link['rel']] = @host + link['href']
       end
       @discovered = true
     end
@@ -101,10 +118,9 @@ module RHEVM
     attr_accessor(:id, :href, :name)
 
     def initialize(client, xml)
-      client.logger << "#{xml}\n"
       @client = client
       @id = xml[:id]
-      @href = @client.base_uri + xml[:href]
+      @href = "#{@client.base_uri}#{xml[:href]}"
       @name = xml.xpath('name').text
     end
   end
@@ -132,8 +148,8 @@ module RHEVM
       @status = xml.xpath('status').text
       @memory = xml.xpath('memory').text
       @profile = xml.xpath('type').text
-      @sockets = xml.xpath('cpu/topology').first[:sockets]
-      @cores = xml.xpath('cpu/topology').first[:cores]
+      @sockets = xml.xpath('cpu/topology').first[:sockets] rescue ''
+      @cores = xml.xpath('cpu/topology').first[:cores] rescue ''
       @bootdevs = []
       xml.xpath('os/boot').each do |boot|
         @bootdevs << boot[:dev]
@@ -141,7 +157,7 @@ module RHEVM
       @host = xml.xpath('host')[:id]
       @cluster = xml.xpath('cluster').first[:id]
       @template = xml.xpath('template').first[:id]
-      @vmpool = xml.xpath('vmpool').first[:id]
+      @vmpool = xml.xpath('vmpool').first[:id] if xml.xpath('vmpool').size >0
       @creation_time = xml.xpath('creation_time').text
     end
   end
-- 
1.7.3.3