memcached (openstack) is no longer in use
[mirror/dsa-puppet.git] / 3rdparty / modules / keystone / lib / puppet / provider / keystone_user / openstack.rb
index 6c8d04a..eb1e303 100644 (file)
@@ -1,6 +1,5 @@
-require 'net/http'
-require 'json'
 require 'puppet/provider/keystone'
+
 Puppet::Type.type(:keystone_user).provide(
   :openstack,
   :parent => Puppet::Provider::Keystone
@@ -8,137 +7,187 @@ Puppet::Type.type(:keystone_user).provide(
 
   desc "Provider to manage keystone users."
 
+  @credentials = Puppet::Provider::Openstack::CredentialsV3.new
+
   def initialize(value={})
     super(value)
     @property_flush = {}
   end
 
   def create
-    properties = []
+    # see if resource[:domain], or user specified as user::domain
+    user_name, user_domain = self.class.name_and_domain(resource[:name], resource[:domain])
+    properties = [user_name]
     if resource[:enabled] == :true
       properties << '--enable'
     elsif resource[:enabled] == :false
       properties << '--disable'
     end
     if resource[:password]
-      properties << '--password'
-      properties << resource[:password]
+      properties << '--password' << resource[:password]
+    end
+    if resource[:email]
+      properties << '--email' << resource[:email]
     end
+    if user_domain
+      properties << '--domain'
+      properties << user_domain
+    end
+    @property_hash = self.class.request('user', 'create', properties)
+    @property_hash[:domain] = user_domain
     if resource[:tenant]
-      properties << '--project'
-      properties << resource[:tenant]
+      # DEPRECATED - To be removed in next release (Liberty)
+      # https://bugs.launchpad.net/puppet-keystone/+bug/1472437
+      project_id = Puppet::Resource.indirection.find("Keystone_tenant/#{resource[:tenant]}")[:id]
+      set_project(resource[:tenant], project_id)
     end
-    if resource[:email]
-      properties << '--email'
-      properties << resource[:email]
+    @property_hash[:ensure] = :present
+  end
+
+  def destroy
+    self.class.request('user', 'delete', id)
+    @property_hash.clear
+  end
+
+  def flush
+    options = []
+    if @property_flush && !@property_flush.empty?
+      options << '--enable'  if @property_flush[:enabled] == :true
+      options << '--disable' if @property_flush[:enabled] == :false
+      # There is a --description flag for the set command, but it does not work if the value is empty
+      options << '--password' << resource[:password] if @property_flush[:password]
+      options << '--email'    << resource[:email]    if @property_flush[:email]
+      # project handled in tenant= separately
+      unless options.empty?
+        options << @property_hash[:id]
+        self.class.request('user', 'set', options)
+      end
+      @property_flush.clear
     end
-    @instance = request('user', 'create', resource[:name], resource[:auth], properties)
   end
 
   def exists?
-    ! instance(resource[:name]).empty?
+    @property_hash[:ensure] == :present
   end
 
-  def destroy
-    request('user', 'delete', resource[:name], resource[:auth])
+  # Types properties
+  def enabled
+    bool_to_sym(@property_hash[:enabled])
   end
 
-
   def enabled=(value)
     @property_flush[:enabled] = value
   end
 
-  def enabled
-    bool_to_sym(instance(resource[:name])[:enabled])
+  def email
+    @property_hash[:email]
   end
 
+  def email=(value)
+    @property_flush[:email] = value
+  end
 
-  def password=(value)
-    @property_flush[:password] = value
+  def id
+    @property_hash[:id]
   end
 
   def password
-    # if we don't know a password we can't test it
-    return nil if resource[:password] == nil
-    # if the user is disabled then the password can't be changed
-    return resource[:password] if resource[:enabled] == :false
-    # if replacing password is disabled, then don't change it
-    return resource[:password] if resource[:replace_password] == :false
-    # we can't get the value of the password but we can test to see if the one we know
-    # about works, if it doesn't then return nil, causing it to be reset
-    endpoint = nil
-    if password_credentials_set?(resource[:auth]) || service_credentials_set?(resource[:auth])
-      endpoint = (resource[:auth])['auth_url']
-    elsif openrc_set?(resource[:auth])
-      endpoint = get_credentials_from_openrc(resource[:auth])['auth_url']
-    elsif env_vars_set?
-      endpoint = ENV['OS_AUTH_URL']
+    res = nil
+    return res if resource[:password] == nil
+    if resource[:enabled] == :false || resource[:replace_password] == :false
+      # Unchanged password
+      res = resource[:password]
     else
-      # try to get endpoint from keystone.conf
-      endpoint = get_admin_endpoint
-    end
-    if endpoint == nil
-      raise(Puppet::Error::OpenstackAuthInputError, 'Could not find auth url to check user password.')
-    else
-      auth_params = {
-        'username'    => resource[:name],
-        'password'    => resource[:password],
-        'tenant_name' => resource[:tenant],
-        'auth_url'    => endpoint,
-      }
-      # LP#1408754
-      # Ideally this would be checked with the `openstack token issue` command,
-      # but that command is not available with version 0.3.0 of openstackclient
-      # which is what ships on Ubuntu during Juno.
-      # Instead we'll check whether the user can authenticate with curl.
-      creds_hash = {
-        :auth => {
-          :passwordCredentials => {
-            :username => auth_params['username'],
-            :password => auth_params['password'],
-          }
-        }
-      }
-      url = URI.parse(endpoint)
-      # There is issue with ipv6 where address has to be in brackets, this causes the
-      # underlying ruby TCPSocket to fail. Net::HTTP.new will fail without brackets on
-      # joining the ipv6 address with :port or passing brackets to TCPSocket. It was
-      # found that if we use Net::HTTP.start with url.hostname the incriminated code
-      # won't be hit.
-      use_ssl = url.scheme == "https" ? true : false
-      http = Net::HTTP.start(url.hostname, url.port, {:use_ssl => use_ssl})
-      request = Net::HTTP::Post.new('/v2.0/tokens')
-      request.body = creds_hash.to_json
-      request.content_type = 'application/json'
-      response = http.request(request)
-      if response.code.to_i == 401 || response.code.to_i == 403 # 401 => unauthorized, 403 => userDisabled
-        return nil
-      elsif ! (response.code == 200 || response.code == 203)
-        return resource[:password]
+      # Password validation
+      credentials                  = Puppet::Provider::Openstack::CredentialsV3.new
+      credentials.auth_url         = self.class.get_endpoint
+      credentials.password         = resource[:password]
+      credentials.user_id          = id
+      # NOTE: The only reason we use username is so that the openstack provider
+      # will know we are doing v3password auth - otherwise, it is not used.  The
+      # user_id uniquely identifies the user including domain.
+      credentials.username, unused = self.class.name_and_domain(resource[:name], domain)
+      # Need to specify a project id to get a project scoped token.  List
+      # all of the projects for the user, and use the id from the first one.
+      projects = self.class.request('project', 'list', ['--user', id, '--long'])
+      if projects && projects[0] && projects[0][:id]
+        credentials.project_id = projects[0][:id]
+      else
+        # last chance - try a domain scoped token
+        credentials.domain_name = domain
+      end
+      begin
+        token = Puppet::Provider::Openstack.request('token', 'issue', ['--format', 'value'], credentials)
+      rescue Puppet::Error::OpenstackUnauthorizedError
+        # password is invalid
       else
-        raise(Puppet::Error, "Received bad response while trying to authenticate user: #{response.body}")
+        res = resource[:password] unless token.empty?
       end
     end
+    return res
   end
 
-  def tenant=(value)
-    begin
-      request('user', 'set', resource[:name], resource[:auth], '--project', value)
-    rescue Puppet::ExecutionFailure => e
-      if e.message =~ /You are not authorized to perform the requested action: LDAP user update/
-        # read-only LDAP identity backend - just fall through
-      else
-        raise e
+  def password=(value)
+    @property_flush[:password] = value
+  end
+
+  def replace_password
+    @property_hash[:replace_password]
+  end
+
+  def replace_password=(value)
+    @property_flush[:replace_password] = value
+  end
+
+  def find_project_for_user(projname, project_id = nil)
+    # DEPRECATED - To be removed in next release (Liberty)
+    # https://bugs.launchpad.net/puppet-keystone/+bug/1472437
+    user_name, user_domain = self.class.name_and_domain(resource[:name], resource[:domain])
+    project_name, project_domain = self.class.name_and_domain(projname, nil, user_domain)
+    self.class.request('project', 'list', ['--user', id, '--long']).each do |project|
+      if (project_id == project[:id]) ||
+         ((projname == project_name) && (project_domain == self.class.domain_name_from_id(project[:domain_id])))
+        return project[:name]
       end
-      # note: read-write ldap will silently fail, not raise an exception
     end
-    set_project(value)
+    return nil
   end
 
+  def set_project(newproject, project_id = nil)
+    # DEPRECATED - To be removed in next release (Liberty)
+    # https://bugs.launchpad.net/puppet-keystone/+bug/1472437
+    unless project_id
+      project_id = Puppet::Resource.indirection.find("Keystone_tenant/#{newproject}")[:id]
+    end
+    # Currently the only way to assign a user to a tenant not using user-create
+    # is to use role-add - this means we also need a role - there is usual
+    # a default role called _member_ which can be used for this purpose.  What
+    # usually happens in a puppet module is that immediately after calling
+    # keystone_user, the module will then assign a role to that user.  It is
+    # ok for a user to have the _member_ role and another role.
+    default_role = "_member_"
+    begin
+      self.class.request('role', 'show', default_role)
+    rescue
+      self.class.request('role', 'create', default_role)
+    end
+    # finally, assign the user to the project with the role
+    self.class.request('role', 'add', [default_role, '--project', project_id, '--user', id])
+    newproject
+  end
+
+  # DEPRECATED - To be removed in next release (Liberty)
+  # https://bugs.launchpad.net/puppet-keystone/+bug/1472437
+  def tenant=(value)
+    @property_hash[:tenant] = set_project(value)
+  end
+
+  # DEPRECATED - To be removed in next release (Liberty)
+  # https://bugs.launchpad.net/puppet-keystone/+bug/1472437
   def tenant
     return resource[:tenant] if sym_to_bool(resource[:ignore_default_tenant])
     # use the one returned from instances
-    tenant_name = instance(resource[:name])[:project]
+    tenant_name = @property_hash[:project]
     if tenant_name.nil? or tenant_name.empty?
       # if none (i.e. ldap backend) use the given one
       tenant_name = resource[:tenant]
@@ -148,105 +197,71 @@ Puppet::Type.type(:keystone_user).provide(
     if tenant_name.nil? or tenant_name.empty?
       return nil # nothing found, nothing given
     end
-    # If the user list command doesn't report the project, it might still be there
-    # We don't need to know exactly what it is, we just need to know whether it's
-    # the one we're trying to set.
-    roles = request('user role', 'list', resource[:name], resource[:auth], ['--project', tenant_name])
-    if roles.empty?
-      return nil
-    else
-      return tenant_name
-    end
-  end
-
-  def replace_password
-    instance(resource[:name])[:replace_password]
+    project_id = Puppet::Resource.indirection.find("Keystone_tenant/#{tenant_name}")[:id]
+    find_project_for_user(tenant_name, project_id)
   end
 
-  def replace_password=(value)
-    @property_flush[:replace_password] = value
+  def domain
+    @property_hash[:domain]
   end
 
-  def email=(value)
-    @property_flush[:email] = value
-  end
-
-  def email
-    instance(resource[:name])[:email]
-  end
-
-  def id
-    instance(resource[:name])[:id]
+  def domain_id
+    @property_hash[:domain_id]
   end
 
   def self.instances
-    list = request('user', 'list', nil, nil, '--long')
-    list.collect do |user|
+    instance_hash = {}
+    request('user', 'list', ['--long']).each do |user|
+      # The field says "domain" but it is really the domain_id
+      domname = domain_name_from_id(user[:domain])
+      if instance_hash.include?(user[:name]) # not unique
+        curdomid = instance_hash[user[:name]][:domain]
+        if curdomid != default_domain_id
+          # Move the user from the short name slot to the long name slot
+          # because it is not in the default domain.
+          curdomname = domain_name_from_id(curdomid)
+          instance_hash["#{user[:name]}::#{curdomname}"] = instance_hash[user[:name]]
+          # Use the short name slot for the new user
+          instance_hash[user[:name]] = user
+        else
+          # Use the long name for the new user
+          instance_hash["#{user[:name]}::#{domname}"] = user
+        end
+      else
+        # Unique (for now) - store in short name slot
+        instance_hash[user[:name]] = user
+      end
+    end
+    instance_hash.keys.collect do |user_name|
+      user = instance_hash[user_name]
       new(
-        :name        => user[:name],
+        :name        => user_name,
         :ensure      => :present,
         :enabled     => user[:enabled].downcase.chomp == 'true' ? true : false,
         :password    => user[:password],
-        :tenant      => user[:project],
         :email       => user[:email],
+        :description => user[:description],
+        :domain      => domain_name_from_id(user[:domain]),
+        :domain_id   => user[:domain],
         :id          => user[:id]
       )
     end
   end
 
-  def instances
-    instances = request('user', 'list', nil, resource[:auth], '--long')
-    instances.collect do |user|
-      {
-        :name        => user[:name],
-        :enabled     => user[:enabled].downcase.chomp == 'true' ? true : false,
-        :password    => user[:password],
-        :project     => user[:project],
-        :email       => user[:email],
-        :id          => user[:id]
-      }
-    end
-  end
-
-  def instance(name)
-    @instance ||= instances.select { |instance| instance[:name] == name }.first || {}
-  end
-
-  def set_project(newproject)
-    # some backends do not store the project/tenant in the user object, so we have to
-    # to modify the project/tenant instead
-    # First, see if the project actually needs to change
-    roles = request('user role', 'list', resource[:name], resource[:auth], ['--project', newproject])
-    unless roles.empty?
-      return # if already set, just skip
-    end
-    # Currently the only way to assign a user to a tenant not using user-create
-    # is to use user-role-add - this means we also need a role - there is usual
-    # a default role called _member_ which can be used for this purpose.  What
-    # usually happens in a puppet module is that immediately after calling
-    # keystone_user, the module will then assign a role to that user.  It is
-    # ok for a user to have the _member_ role and another role.
-    default_role = "_member_"
-    begin
-      request('role', 'show', default_role, resource[:auth])
-    rescue
-      debug("Keystone role #{default_role} does not exist - creating")
-      request('role', 'create', default_role, resource[:auth])
-    end
-    request('role', 'add', default_role, resource[:auth],
-            '--project', newproject, '--user', resource[:name])
-  end
-
-  def flush
-    options = []
-    if @property_flush
-      (options << '--enable') if @property_flush[:enabled] == :true
-      (options << '--disable') if @property_flush[:enabled] == :false
-      # There is a --description flag for the set command, but it does not work if the value is empty
-      (options << '--password' << resource[:password]) if @property_flush[:password]
-      (options << '--email'    << resource[:email])    if @property_flush[:email]
-      # project handled in tenant= separately
-      request('user', 'set', resource[:name], resource[:auth], options) unless options.empty?
+  def self.prefetch(resources)
+    users = instances
+    resources.each do |resname, resource|
+      # resname may be specified as just "name" or "name::domain"
+      name, resdomain = name_and_domain(resname, resource[:domain])
+      provider = users.find do |user|
+        # have a match if the full instance name matches the full resource name, OR
+        # the base resource name matches the base instance name, and the
+        # resource domain matches the instance domain
+        username, user_domain = name_and_domain(user.name, user.domain)
+        (user.name == resname) ||
+          ((username == name) && (user_domain == resdomain))
+      end
+      resource.provider = provider if provider
     end
   end