From 682c8e0b5c182679b98c80d4733b046d25ca47a5 Mon Sep 17 00:00:00 2001 From: Pedro Algarvio Date: Wed, 11 Dec 2013 10:17:05 +0000 Subject: [PATCH 1/2] The `stdlib` is good enough. Check additional IP information providers. --- salt/grains/external_ip.py | 55 ++++++++++++++++++++++++++++---------- 1 file changed, 41 insertions(+), 14 deletions(-) diff --git a/salt/grains/external_ip.py b/salt/grains/external_ip.py index 39164f2a30..e4879ae0ad 100644 --- a/salt/grains/external_ip.py +++ b/salt/grains/external_ip.py @@ -1,20 +1,47 @@ -try: - import requests - HAS_REQUESTS = True -except ImportError: - HAS_REQUESTS = False +# -*- coding: utf-8 -*- +''' + :codeauthor: Jeff Frost + :copyright: © 2013 by the SaltStack Team, see AUTHORS for more details. + :license: Apache 2.0, see LICENSE for more details. + + + salt.grains.external_ip + ~~~~~~~~~~~~~~~~~~~~~~~ + + Return the external IP address reported by one of the following providers: + + * ipecho.net + * externalip.net + * ident.me + + Which ever reports a valid IP first +''' + +# Import Python Libs +import urllib2 +import contextlib + +# Import salt libs +from salt.utils.validate.net import ipv4_addr as _ipv4_addr + def external_ip(): ''' - Return the external IP address reported by ipecho.net + Return the external IP address ''' + check_ips = ('http://ipecho.net/plain', + 'http://api.externalip.net/ip', + 'http://v4.ident.me') - if not HAS_REQUESTS: - return {} + for check_ip in check_ips: + try: + with contextlib.closing(urllib2.urlopen(check_ip)) as req: + ip_ = req.read().strip() + if not _ipv4_addr(ip_): + continue + return {'external_ip': ip_} + except urllib2.HTTPError: + continue - try: - r = requests.get('http://ipecho.net/plain') - ip = r.content - except Exception: - ip = [] - return {'external_ip': ip} + # Return an empty value as a last resort + return {'external_ip': []} From 3048a9f29b19ce427dfbb4974278b81a9fda46ed Mon Sep 17 00:00:00 2001 From: Pedro Algarvio Date: Wed, 11 Dec 2013 10:20:00 +0000 Subject: [PATCH 2/2] Only wait at most 3 seconds for a reply --- salt/grains/external_ip.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/salt/grains/external_ip.py b/salt/grains/external_ip.py index e4879ae0ad..92eb7c33d4 100644 --- a/salt/grains/external_ip.py +++ b/salt/grains/external_ip.py @@ -33,9 +33,9 @@ def external_ip(): 'http://api.externalip.net/ip', 'http://v4.ident.me') - for check_ip in check_ips: + for url in check_ips: try: - with contextlib.closing(urllib2.urlopen(check_ip)) as req: + with contextlib.closing(urllib2.urlopen(url, timeout=3)) as req: ip_ = req.read().strip() if not _ipv4_addr(ip_): continue