Please, see the modified patch attached.

Standa

On 11/27/2015 03:48 PM, Martin Basti wrote:


On 27.11.2015 15:33, Petr Spacek wrote:
On 27.11.2015 15:32, Martin Basti wrote:

On 25.11.2015 17:18, Stanislav Laznicka wrote:
There were two functions for the same purpose. Removed one.


Hello,

I would like to have "log" param of is_host_resolvable as optional
Is there an immediate need for the optional param? If not, I would not clutter
the code.

So at least I would like to move log param as the last param, in case of need it can be modified to optional parameter.

Or log can be default as root_logger, IMO we us only root_logger everywhere, but this need investigation.

Martin

From 93565a54d02ac05b686c18074d95e899610bcdc3 Mon Sep 17 00:00:00 2001
From: Stanislav Laznicka <slazn...@redhat.com>
Date: Wed, 25 Nov 2015 16:38:00 +0100
Subject: [PATCH] Removed duplicate domain name validating function

---
 ipa-client/ipa-install/ipa-client-install |  9 +++++---
 ipalib/plugins/dns.py                     | 22 ++++++++++++-------
 ipalib/plugins/host.py                    |  2 +-
 ipalib/plugins/service.py                 |  2 +-
 ipalib/util.py                            | 35 +++++++++++++++----------------
 ipapython/ipautil.py                      | 12 -----------
 6 files changed, 39 insertions(+), 43 deletions(-)

diff --git a/ipa-client/ipa-install/ipa-client-install b/ipa-client/ipa-install/ipa-client-install
index 05a550b..f6d66c7 100755
--- a/ipa-client/ipa-install/ipa-client-install
+++ b/ipa-client/ipa-install/ipa-client-install
@@ -54,6 +54,7 @@ try:
     from ipapython.config import IPAOptionParser
     from ipalib import api, errors
     from ipalib import x509, certstore
+    from ipalib.util import is_host_resolvable
     from ipalib.constants import CACERT
     from ipapython.dn import DN
     from ipapython.ssh import SSHPublicKey
@@ -1761,11 +1762,13 @@ def get_server_connection_interface(server):
 
 def client_dns(server, hostname, options):
 
-    dns_ok = ipautil.is_host_resolvable(hostname)
-
-    if not dns_ok:
+    try:
+        is_host_resolvable(hostname, root_logger)
+        dns_ok = True
+    except errors.DNSNotARecordError:
         root_logger.warning("Hostname (%s) does not have A/AAAA record.",
                             hostname)
+        dns_ok = False
 
     if (options.dns_updates or options.all_ip_addresses or options.ip_addresses
             or not dns_ok):
diff --git a/ipalib/plugins/dns.py b/ipalib/plugins/dns.py
index 830a70f..6a63c3c 100644
--- a/ipalib/plugins/dns.py
+++ b/ipalib/plugins/dns.py
@@ -51,9 +51,10 @@ from ipalib.util import (normalize_zonemgr,
                          DNSSECSignatureMissingError, UnresolvableRecordError,
                          EDNS0UnsupportedError, DNSSECValidationError,
                          validate_dnssec_zone_forwarder_step1,
-                         validate_dnssec_zone_forwarder_step2)
+                         validate_dnssec_zone_forwarder_step2,
+                         is_host_resolvable)
 
-from ipapython.ipautil import CheckedIPAddress, is_host_resolvable
+from ipapython.ipautil import CheckedIPAddress
 from ipapython.dnsutil import DNSName
 
 if six.PY3:
@@ -1554,7 +1555,7 @@ _dns_record_options = tuple(__dns_record_options_iter())
 _dns_supported_record_types = tuple(record.rrtype for record in _dns_records \
                                     if record.supported)
 
-def check_ns_rec_resolvable(zone, name):
+def check_ns_rec_resolvable(zone, name, log):
     assert isinstance(zone, DNSName)
     assert isinstance(name, DNSName)
 
@@ -1563,7 +1564,9 @@ def check_ns_rec_resolvable(zone, name):
     elif not name.is_absolute():
         # this is a DNS name relative to the zone
         name = name.derelativize(zone.make_absolute())
-    if not is_host_resolvable(name):
+    try:
+        is_host_resolvable(name, log)
+    except errors.DNSNotARecordError:
         raise errors.NotFound(
             reason=_('Nameserver \'%(host)s\' does not have a corresponding '
                      'A/AAAA record') % {'host': name}
@@ -2734,7 +2737,8 @@ class dnszone_add(DNSZoneBase_add):
 
             # verify if user specified server is resolvable
             if not options['force']:
-                check_ns_rec_resolvable(keys[0], entry_attrs['idnssoamname'])
+                check_ns_rec_resolvable(keys[0], entry_attrs['idnssoamname'],
+                                        self.log)
             # show warning about --name-server option
             context.show_warning_nameserver_option = True
         else:
@@ -2833,7 +2837,7 @@ class dnszone_mod(DNSZoneBase_mod):
             nameserver = entry_attrs['idnssoamname']
             if nameserver:
                 if not nameserver.is_empty() and not options['force']:
-                    check_ns_rec_resolvable(keys[0], nameserver)
+                    check_ns_rec_resolvable(keys[0], nameserver, self.log)
                 context.show_warning_nameserver_option = True
             else:
                 # empty value, this option is required by ldap
@@ -3004,7 +3008,7 @@ class dnsrecord(LDAPObject):
         if options.get('force', False) or nsrecords is None:
             return
         for nsrecord in nsrecords:
-            check_ns_rec_resolvable(keys[0], DNSName(nsrecord))
+            check_ns_rec_resolvable(keys[0], DNSName(nsrecord), self.log)
 
     def _idnsname_pre_callback(self, ldap, dn, entry_attrs, *keys, **options):
         assert isinstance(dn, DN)
@@ -4196,7 +4200,9 @@ class dns_resolve(Command):
     def execute(self, *args, **options):
         query=args[0]
 
-        if not is_host_resolvable(query):
+        try:
+            is_host_resolvable(query, self.log)
+        except errors.DNSNotARecordError:
             raise errors.NotFound(
                 reason=_('Host \'%(host)s\' not found') % {'host': query}
             )
diff --git a/ipalib/plugins/host.py b/ipalib/plugins/host.py
index bceab31..95cf60c 100644
--- a/ipalib/plugins/host.py
+++ b/ipalib/plugins/host.py
@@ -625,7 +625,7 @@ class host_add(LDAPCreate):
                     check_forward=True,
                     check_reverse=check_reverse)
         if not options.get('force', False) and not 'ip_address' in options:
-            util.validate_host_dns(self.log, keys[-1])
+            util.is_host_resolvable(keys[-1], self.log)
         if 'locality' in entry_attrs:
             entry_attrs['l'] = entry_attrs['locality']
         entry_attrs['cn'] = keys[-1]
diff --git a/ipalib/plugins/service.py b/ipalib/plugins/service.py
index d63e00b..39b782e 100644
--- a/ipalib/plugins/service.py
+++ b/ipalib/plugins/service.py
@@ -554,7 +554,7 @@ class service_add(LDAPCreate):
              # We know the host exists if we've gotten this far but we
              # really want to discourage creating services for hosts that
              # don't exist in DNS.
-             util.validate_host_dns(self.log, hostname)
+             util.is_host_resolvable(hostname, self.log)
         if not 'managedby' in entry_attrs:
             entry_attrs['managedby'] = hostresult['dn']
 
diff --git a/ipalib/util.py b/ipalib/util.py
index 89d67e6..838a24f 100644
--- a/ipalib/util.py
+++ b/ipalib/util.py
@@ -66,32 +66,31 @@ def json_serialize(obj):
         return ''
     return json_serialize(obj.__json__())
 
-def validate_host_dns(log, fqdn):
+def is_host_resolvable(fqdn, log):
     """
     See if the hostname has a DNS A/AAAA record.
     """
-    try:
-        answers = resolver.query(fqdn, rdatatype.A)
-        log.debug(
-            'IPA: found %d A records for %s: %s' % (len(answers), fqdn,
-                ' '.join(str(answer) for answer in answers))
-        )
-    except DNSException as e:
-        log.debug(
-            'IPA: DNS A record lookup failed for %s' % fqdn
-        )
-        # A record not found, try to find AAAA record
+    if not isinstance(fqdn, DNSName):
+        fqdn = DNSName(fqdn)
+
+    fqdn = fqdn.make_absolute()
+    for rdtype in ('A', 'AAAA'):
         try:
-            answers = resolver.query(fqdn, rdatatype.AAAA)
+            answers = resolver.query(fqdn, rdtype)
             log.debug(
-                'IPA: found %d AAAA records for %s: %s' % (len(answers), fqdn,
-                    ' '.join(str(answer) for answer in answers))
+                'IPA: found %d %s records for %s: %s' % (len(answers),
+                rdtype, fqdn, ' '.join(str(answer) for answer in answers))
             )
-        except DNSException as e:
+        except DNSException:
             log.debug(
-                'IPA: DNS AAAA record lookup failed for %s' % fqdn
+                'IPA: DNS %s record lookup failed for %s' %
+                (rdtype, fqdn)
             )
-            raise errors.DNSNotARecordError()
+            continue
+        else:
+            return
+    # dns lookup failed in both tries
+    raise errors.DNSNotARecordError()
 
 
 def has_soa_or_ns_record(domain):
diff --git a/ipapython/ipautil.py b/ipapython/ipautil.py
index 4551ea5..104f9d1 100644
--- a/ipapython/ipautil.py
+++ b/ipapython/ipautil.py
@@ -911,18 +911,6 @@ def bind_port_responder(port, socket_type=socket.SOCK_STREAM, socket_timeout=Non
     if s is None and last_socket_error is not None:
         raise last_socket_error # pylint: disable=E0702
 
-def is_host_resolvable(fqdn):
-    if not isinstance(fqdn, DNSName):
-        fqdn = DNSName(fqdn)
-    for rdtype in (rdatatype.A, rdatatype.AAAA):
-        try:
-            resolver.query(fqdn.make_absolute(), rdtype)
-        except DNSException:
-            continue
-        else:
-            return True
-
-    return False
 
 def host_exists(host):
     """
-- 
2.5.0

-- 
Manage your subscription for the Freeipa-devel mailing list:
https://www.redhat.com/mailman/listinfo/freeipa-devel
Contribute to FreeIPA: http://www.freeipa.org/page/Contribute/Code

Reply via email to