4 # Copyright (C) 2010 Google Inc.
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 # General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22 """Ganeti network utility module.
24 This module holds functions that can be used in both daemons (all) and
25 the command line scripts.
36 from ganeti import constants
37 from ganeti import errors
39 # Structure definition for getsockopt(SOL_SOCKET, SO_PEERCRED, ...):
40 # struct ucred { pid_t pid; uid_t uid; gid_t gid; };
42 # The GNU C Library defines gid_t and uid_t to be "unsigned int" and
45 # IEEE Std 1003.1-2008:
46 # "nlink_t, uid_t, gid_t, and id_t shall be integer types"
47 # "blksize_t, pid_t, and ssize_t shall be signed integer types"
49 _STRUCT_UCRED_SIZE = struct.calcsize(_STRUCT_UCRED)
52 def GetSocketCredentials(sock):
53 """Returns the credentials of the foreign process connected to a socket.
55 @param sock: Unix socket
56 @rtype: tuple; (number, number, number)
57 @return: The PID, UID and GID of the connected foreign process.
60 peercred = sock.getsockopt(socket.SOL_SOCKET, IN.SO_PEERCRED,
62 return struct.unpack(_STRUCT_UCRED, peercred)
65 def GetHostname(name=None, family=None):
66 """Returns a Hostname object.
69 @param name: hostname or None
71 @param family: AF_INET | AF_INET6 | None
73 @return: Hostname object
74 @raise errors.OpPrereqError: in case of errors in resolving
78 return Hostname(name=name, family=family)
79 except errors.ResolverError, err:
80 raise errors.OpPrereqError("The given name (%s) does not resolve: %s" %
81 (err[0], err[2]), errors.ECODE_RESOLVER)
85 """Class implementing resolver and hostname functionality.
88 _VALID_NAME_RE = re.compile("^[a-z0-9._-]{1,255}$")
90 def __init__(self, name=None, family=None):
91 """Initialize the host name object.
93 If the name argument is None, it will use this system's name.
96 @param family: AF_INET | AF_INET6 | None
98 @param name: hostname or None
101 self.name = self.GetNormalizedName(self.GetFqdn(name))
102 self.ip = self.GetIP(self.name, family=family)
106 """Legacy method the get the current system's name.
112 def GetFqdn(hostname=None):
115 If hostname is None the system's fqdn is returned.
118 @param hostname: name to be fqdn'ed
120 @return: fqdn of given name, if it exists, unmodified name otherwise
124 return socket.getfqdn()
126 return socket.getfqdn(hostname)
129 def GetIP(hostname, family=None):
130 """Return IP address of given hostname.
132 Supports both IPv4 and IPv6.
135 @param hostname: hostname to look up
137 @param family: AF_INET | AF_INET6 | None
140 @raise errors.ResolverError: in case of errors in resolving
144 if family in (socket.AF_INET, socket.AF_INET6):
145 result = socket.getaddrinfo(hostname, None, family)
147 result = socket.getaddrinfo(hostname, None)
148 except (socket.gaierror, socket.herror, socket.error), err:
149 # hostname not found in DNS, or other socket exception in the
150 # (code, description format)
151 raise errors.ResolverError(hostname, err.args[0], err.args[1])
153 # getaddrinfo() returns a list of 5-tupes (family, socktype, proto,
154 # canonname, sockaddr). We return the first tuple's first address in
157 return result[0][4][0]
158 except IndexError, err:
159 raise errors.ResolverError("Unknown error in getaddrinfo(): %s" % err)
162 def GetNormalizedName(cls, hostname):
163 """Validate and normalize the given hostname.
165 @attention: the validation is a bit more relaxed than the standards
166 require; most importantly, we allow underscores in names
167 @raise errors.OpPrereqError: when the name is not valid
170 hostname = hostname.lower()
171 if (not cls._VALID_NAME_RE.match(hostname) or
172 # double-dots, meaning empty label
174 # empty initial label
175 hostname.startswith(".")):
176 raise errors.OpPrereqError("Invalid hostname '%s'" % hostname,
178 if hostname.endswith("."):
179 hostname = hostname.rstrip(".")
183 def TcpPing(target, port, timeout=10, live_port_needed=False, source=None):
184 """Simple ping implementation using TCP connect(2).
186 Check if the given IP is reachable by doing attempting a TCP connect
190 @param target: the IP to ping
192 @param port: the port to connect to
194 @param timeout: the timeout on the connection attempt
195 @type live_port_needed: boolean
196 @param live_port_needed: whether a closed port will cause the
197 function to return failure, as if there was a timeout
198 @type source: str or None
199 @param source: if specified, will cause the connect to be made
200 from this specific source address; failures to bind other
201 than C{EADDRNOTAVAIL} will be ignored
205 family = IPAddress.GetAddressFamily(target)
206 except errors.GenericError:
209 sock = socket.socket(family, socket.SOCK_STREAM)
212 if source is not None:
214 sock.bind((source, 0))
215 except socket.error, (errcode, _):
216 if errcode == errno.EADDRNOTAVAIL:
219 sock.settimeout(timeout)
222 sock.connect((target, port))
225 except socket.timeout:
227 except socket.error, (errcode, _):
228 success = (not live_port_needed) and (errcode == errno.ECONNREFUSED)
233 def GetDaemonPort(daemon_name):
234 """Get the daemon port for this cluster.
236 Note that this routine does not read a ganeti-specific file, but
237 instead uses C{socket.getservbyname} to allow pre-customization of
238 this parameter outside of Ganeti.
240 @type daemon_name: string
241 @param daemon_name: daemon name (in constants.DAEMONS_PORTS)
245 if daemon_name not in constants.DAEMONS_PORTS:
246 raise errors.ProgrammerError("Unknown daemon: %s" % daemon_name)
248 (proto, default_port) = constants.DAEMONS_PORTS[daemon_name]
250 port = socket.getservbyname(daemon_name, proto)
257 class IPAddress(object):
258 """Class that represents an IP address.
266 def _GetIPIntFromString(address):
267 """Abstract method to please pylint.
270 raise NotImplementedError
273 def IsValid(cls, address):
274 """Validate a IP address.
277 @param address: IP address to be checked
279 @return: True if valid, False otherwise
282 if cls.family is None:
284 family = cls.GetAddressFamily(address)
285 except errors.IPAddressError:
291 socket.inet_pton(family, address)
297 def Own(cls, address):
298 """Check if the current host has the the given IP address.
300 This is done by trying to bind the given address. We return True if we
301 succeed or false if a socket.error is raised.
304 @param address: IP address to be checked
306 @return: True if we own the address, False otherwise
309 if cls.family is None:
311 family = cls.GetAddressFamily(address)
312 except errors.IPAddressError:
317 s = socket.socket(family, socket.SOCK_DGRAM)
330 def InNetwork(cls, cidr, address):
331 """Determine whether an address is within a network.
334 @param cidr: Network in CIDR notation, e.g. '192.0.2.0/24', '2001:db8::/64'
336 @param address: IP address
338 @return: True if address is in cidr, False otherwise
341 address_int = cls._GetIPIntFromString(address)
342 subnet = cidr.split("/")
343 assert len(subnet) == 2
345 prefix = int(subnet[1])
349 assert 0 <= prefix <= cls.iplen
350 target_int = cls._GetIPIntFromString(subnet[0])
351 # Convert prefix netmask to integer value of netmask
352 netmask_int = (2**cls.iplen)-1 ^ ((2**cls.iplen)-1 >> prefix)
354 hostmask_int = netmask_int ^ (2**cls.iplen)-1
355 # Calculate network address by and'ing netmask
356 network_int = target_int & netmask_int
357 # Calculate broadcast address by or'ing hostmask
358 broadcast_int = target_int | hostmask_int
360 return network_int <= address_int <= broadcast_int
363 def GetAddressFamily(address):
364 """Get the address family of the given address.
367 @param address: ip address whose family will be returned
369 @return: socket.AF_INET or socket.AF_INET6
370 @raise errors.GenericError: for invalid addresses
374 return IP4Address(address).family
375 except errors.IPAddressError:
379 return IP6Address(address).family
380 except errors.IPAddressError:
383 raise errors.IPAddressError("Invalid address '%s'" % address)
386 def IsLoopback(cls, address):
387 """Determine whether it is a loopback address.
390 @param address: IP address to be checked
392 @return: True if loopback, False otherwise
396 return cls.InNetwork(cls.loopback_cidr, address)
397 except errors.IPAddressError:
401 class IP4Address(IPAddress):
402 """IPv4 address class.
406 family = socket.AF_INET
407 loopback_cidr = "127.0.0.0/8"
409 def __init__(self, address):
410 """Constructor for IPv4 address.
413 @param address: IP address
414 @raises errors.IPAddressError: if address invalid
417 IPAddress.__init__(self)
418 if not self.IsValid(address):
419 raise errors.IPAddressError("IPv4 Address %s invalid" % address)
421 self.address = address
424 def _GetIPIntFromString(address):
425 """Get integer value of IPv4 address.
428 @param address: IPv6 address
430 @return: integer value of given IP address
434 parts = address.split(".")
435 assert len(parts) == 4
437 address_int = (address_int << 8) | int(part)
442 class IP6Address(IPAddress):
443 """IPv6 address class.
447 family = socket.AF_INET6
448 loopback_cidr = "::1/128"
450 def __init__(self, address):
451 """Constructor for IPv6 address.
454 @param address: IP address
455 @raises errors.IPAddressError: if address invalid
458 IPAddress.__init__(self)
459 if not self.IsValid(address):
460 raise errors.IPAddressError("IPv6 Address [%s] invalid" % address)
461 self.address = address
464 def _GetIPIntFromString(address):
465 """Get integer value of IPv6 address.
468 @param address: IPv6 address
470 @return: integer value of given IP address
473 doublecolons = address.count("::")
474 assert not doublecolons > 1
475 if doublecolons == 1:
476 # We have a shorthand address, expand it
478 twoparts = address.split("::")
479 sep = len(twoparts[0].split(':')) + len(twoparts[1].split(':'))
480 parts = twoparts[0].split(':')
481 [parts.append("0") for _ in range(8 - sep)]
482 parts += twoparts[1].split(':')
484 parts = address.split(":")
488 address_int = (address_int << 16) + int(part or '0', 16)
493 def FormatAddress(address, family=None):
494 """Format a socket address
496 @type address: family specific (usually tuple)
497 @param address: address, as reported by this class
498 @type family: integer
499 @param family: socket family (one of socket.AF_*) or None
504 family = IPAddress.GetAddressFamily(address[0])
505 except errors.IPAddressError:
506 raise errors.ParameterError(address)
508 if family == socket.AF_UNIX and len(address) == 3:
509 return "pid=%s, uid=%s, gid=%s" % address
511 if family in (socket.AF_INET, socket.AF_INET6) and len(address) == 2:
513 if family == socket.AF_INET6:
523 raise errors.ParameterError(family, address)