445
439
runtime_expansions = ("approval_delay", "approval_duration",
446
"created", "enabled", "expires",
447
"fingerprint", "host", "interval",
448
"last_approval_request", "last_checked_ok",
440
"created", "enabled", "fingerprint",
441
"host", "interval", "last_checked_ok",
449
442
"last_enabled", "name", "timeout")
450
client_defaults = { "timeout": "PT5M",
451
"extended_timeout": "PT15M",
443
client_defaults = { "timeout": "5m",
444
"extended_timeout": "15m",
453
446
"checker": "fping -q -- %%(host)s",
455
"approval_delay": "PT0S",
456
"approval_duration": "PT1S",
448
"approval_delay": "0s",
449
"approval_duration": "1s",
457
450
"approved_by_default": "True",
458
451
"enabled": "True",
577
570
if getattr(self, "enabled", False):
578
571
# Already enabled
573
self.send_changedstate()
580
574
self.expires = datetime.datetime.utcnow() + self.timeout
581
575
self.enabled = True
582
576
self.last_enabled = datetime.datetime.utcnow()
583
577
self.init_checker()
584
self.send_changedstate()
586
579
def disable(self, quiet=True):
587
580
"""Disable this client."""
588
581
if not getattr(self, "enabled", False):
584
self.send_changedstate()
591
586
logger.info("Disabling client %s", self.name)
592
if getattr(self, "disable_initiator_tag", None) is not None:
587
if getattr(self, "disable_initiator_tag", False):
593
588
gobject.source_remove(self.disable_initiator_tag)
594
589
self.disable_initiator_tag = None
595
590
self.expires = None
596
if getattr(self, "checker_initiator_tag", None) is not None:
591
if getattr(self, "checker_initiator_tag", False):
597
592
gobject.source_remove(self.checker_initiator_tag)
598
593
self.checker_initiator_tag = None
599
594
self.stop_checker()
600
595
self.enabled = False
602
self.send_changedstate()
603
596
# Do not run this again if called by a gobject.timeout_add
669
657
If a checker already exists, leave it running and do
671
659
# The reason for not killing a running checker is that if we
672
# did that, and if a checker (for some reason) started running
673
# slowly and taking more than 'interval' time, then the client
674
# would inevitably timeout, since no checker would get a
675
# chance to run to completion. If we instead leave running
660
# did that, then if a checker (for some reason) started
661
# running slowly and taking more than 'interval' time, the
662
# client would inevitably timeout, since no checker would get
663
# a chance to run to completion. If we instead leave running
676
664
# checkers alone, the checker would have to take more time
677
665
# than 'timeout' for the client to be disabled, which is as it
692
680
self.current_checker_command)
693
681
# Start a new checker if needed
694
682
if self.checker is None:
695
# Escape attributes for the shell
696
escaped_attrs = dict(
697
(attr, re.escape(unicode(getattr(self, attr))))
699
self.runtime_expansions)
701
command = self.checker_command % escaped_attrs
702
except TypeError as error:
703
logger.error('Could not format string "%s"',
704
self.checker_command, exc_info=error)
705
return True # Try again later
684
# In case checker_command has exactly one % operator
685
command = self.checker_command % self.host
687
# Escape attributes for the shell
688
escaped_attrs = dict(
690
re.escape(unicode(str(getattr(self, attr, "")),
694
self.runtime_expansions)
697
command = self.checker_command % escaped_attrs
698
except TypeError as error:
699
logger.error('Could not format string "%s"',
700
self.checker_command, exc_info=error)
701
return True # Try again later
706
702
self.current_checker_command = command
708
704
logger.info("Starting checker %r for %s",
714
710
self.checker = subprocess.Popen(command,
716
712
shell=True, cwd="/")
713
self.checker_callback_tag = (gobject.child_watch_add
715
self.checker_callback,
717
# The checker may have completed before the gobject
718
# watch was added. Check for this.
719
pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
721
gobject.source_remove(self.checker_callback_tag)
722
self.checker_callback(pid, status, command)
717
723
except OSError as error:
718
724
logger.error("Failed to start subprocess",
721
self.checker_callback_tag = (gobject.child_watch_add
723
self.checker_callback,
725
# The checker may have completed before the gobject
726
# watch was added. Check for this.
728
pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
729
except OSError as error:
730
if error.errno == errno.ECHILD:
731
# This should never happen
732
logger.error("Child process vanished",
737
gobject.source_remove(self.checker_callback_tag)
738
self.checker_callback(pid, status, command)
739
726
# Re-run this periodically if run by gobject.timeout_add
1540
1527
def Timeout_dbus_property(self, value=None):
1541
1528
if value is None: # get
1542
1529
return dbus.UInt64(self.timeout_milliseconds())
1543
old_timeout = self.timeout
1544
1530
self.timeout = datetime.timedelta(0, 0, 0, value)
1545
# Reschedule disabling
1531
# Reschedule timeout
1546
1532
if self.enabled:
1547
1533
now = datetime.datetime.utcnow()
1548
self.expires += self.timeout - old_timeout
1549
if self.expires <= now:
1534
time_to_die = timedelta_to_milliseconds(
1535
(self.last_checked_ok + self.timeout) - now)
1536
if time_to_die <= 0:
1550
1537
# The timeout has passed
1540
self.expires = (now +
1541
datetime.timedelta(milliseconds =
1553
1543
if (getattr(self, "disable_initiator_tag", None)
1556
1546
gobject.source_remove(self.disable_initiator_tag)
1557
self.disable_initiator_tag = (
1558
gobject.timeout_add(
1559
timedelta_to_milliseconds(self.expires - now),
1547
self.disable_initiator_tag = (gobject.timeout_add
1562
1551
# ExtendedTimeout - property
1563
1552
@dbus_service_property(_interface, signature="t",
1909
1899
use_ipv6: Boolean; to use IPv6 or not
1911
1901
def __init__(self, server_address, RequestHandlerClass,
1912
interface=None, use_ipv6=True, socketfd=None):
1913
"""If socketfd is set, use that file descriptor instead of
1914
creating a new one with socket.socket().
1902
interface=None, use_ipv6=True):
1916
1903
self.interface = interface
1918
1905
self.address_family = socket.AF_INET6
1919
if socketfd is not None:
1920
# Save the file descriptor
1921
self.socketfd = socketfd
1922
# Save the original socket.socket() function
1923
self.socket_socket = socket.socket
1924
# To implement --socket, we monkey patch socket.socket.
1926
# (When socketserver.TCPServer is a new-style class, we
1927
# could make self.socket into a property instead of monkey
1928
# patching socket.socket.)
1930
# Create a one-time-only replacement for socket.socket()
1931
@functools.wraps(socket.socket)
1932
def socket_wrapper(*args, **kwargs):
1933
# Restore original function so subsequent calls are
1935
socket.socket = self.socket_socket
1936
del self.socket_socket
1937
# This time only, return a new socket object from the
1938
# saved file descriptor.
1939
return socket.fromfd(self.socketfd, *args, **kwargs)
1940
# Replace socket.socket() function with wrapper
1941
socket.socket = socket_wrapper
1942
# The socketserver.TCPServer.__init__ will call
1943
# socket.socket(), which might be our replacement,
1944
# socket_wrapper(), if socketfd was set.
1945
1906
socketserver.TCPServer.__init__(self, server_address,
1946
1907
RequestHandlerClass)
1948
1908
def server_bind(self):
1949
1909
"""This overrides the normal server_bind() function
1950
1910
to bind to an interface if one was specified, and also NOT to
1959
1919
self.socket.setsockopt(socket.SOL_SOCKET,
1960
1920
SO_BINDTODEVICE,
1961
str(self.interface + '\0'))
1962
1923
except socket.error as error:
1963
if error.errno == errno.EPERM:
1964
logger.error("No permission to bind to"
1965
" interface %s", self.interface)
1966
elif error.errno == errno.ENOPROTOOPT:
1924
if error[0] == errno.EPERM:
1925
logger.error("No permission to"
1926
" bind to interface %s",
1928
elif error[0] == errno.ENOPROTOOPT:
1967
1929
logger.error("SO_BINDTODEVICE not available;"
1968
1930
" cannot bind to interface %s",
1969
1931
self.interface)
1970
elif error.errno == errno.ENODEV:
1971
logger.error("Interface %s does not exist,"
1972
" cannot bind", self.interface)
1975
1934
# Only bind(2) the socket if we really need to.
2036
1994
def handle_ipc(self, source, condition, parent_pipe=None,
2037
1995
proc = None, client_object=None):
1997
gobject.IO_IN: "IN", # There is data to read.
1998
gobject.IO_OUT: "OUT", # Data can be written (without
2000
gobject.IO_PRI: "PRI", # There is urgent data to read.
2001
gobject.IO_ERR: "ERR", # Error condition.
2002
gobject.IO_HUP: "HUP" # Hung up (the connection has been
2003
# broken, usually for pipes and
2006
conditions_string = ' | '.join(name
2008
condition_names.iteritems()
2009
if cond & condition)
2038
2010
# error, or the other end of multiprocessing.Pipe has closed
2039
if condition & (gobject.IO_ERR | gobject.IO_HUP):
2011
if condition & (gobject.IO_ERR | condition & gobject.IO_HUP):
2040
2012
# Wait for other process to exit
2103
def rfc3339_duration_to_delta(duration):
2104
"""Parse an RFC 3339 "duration" and return a datetime.timedelta
2106
>>> rfc3339_duration_to_delta("P7D")
2107
datetime.timedelta(7)
2108
>>> rfc3339_duration_to_delta("PT60S")
2109
datetime.timedelta(0, 60)
2110
>>> rfc3339_duration_to_delta("PT60M")
2111
datetime.timedelta(0, 3600)
2112
>>> rfc3339_duration_to_delta("PT24H")
2113
datetime.timedelta(1)
2114
>>> rfc3339_duration_to_delta("P1W")
2115
datetime.timedelta(7)
2116
>>> rfc3339_duration_to_delta("PT5M30S")
2117
datetime.timedelta(0, 330)
2118
>>> rfc3339_duration_to_delta("P1DT3M20S")
2119
datetime.timedelta(1, 200)
2122
# Parsing an RFC 3339 duration with regular expressions is not
2123
# possible - there would have to be multiple places for the same
2124
# values, like seconds. The current code, while more esoteric, is
2125
# cleaner without depending on a parsing library. If Python had a
2126
# built-in library for parsing we would use it, but we'd like to
2127
# avoid excessive use of external libraries.
2129
# New type for defining tokens, syntax, and semantics all-in-one
2130
Token = collections.namedtuple("Token",
2131
("regexp", # To match token; if
2132
# "value" is not None,
2133
# must have a "group"
2135
"value", # datetime.timedelta or
2137
"followers")) # Tokens valid after
2139
# RFC 3339 "duration" tokens, syntax, and semantics; taken from
2140
# the "duration" ABNF definition in RFC 3339, Appendix A.
2141
token_end = Token(re.compile(r"$"), None, frozenset())
2142
token_second = Token(re.compile(r"(\d+)S"),
2143
datetime.timedelta(seconds=1),
2144
frozenset((token_end,)))
2145
token_minute = Token(re.compile(r"(\d+)M"),
2146
datetime.timedelta(minutes=1),
2147
frozenset((token_second, token_end)))
2148
token_hour = Token(re.compile(r"(\d+)H"),
2149
datetime.timedelta(hours=1),
2150
frozenset((token_minute, token_end)))
2151
token_time = Token(re.compile(r"T"),
2153
frozenset((token_hour, token_minute,
2155
token_day = Token(re.compile(r"(\d+)D"),
2156
datetime.timedelta(days=1),
2157
frozenset((token_time, token_end)))
2158
token_month = Token(re.compile(r"(\d+)M"),
2159
datetime.timedelta(weeks=4),
2160
frozenset((token_day, token_end)))
2161
token_year = Token(re.compile(r"(\d+)Y"),
2162
datetime.timedelta(weeks=52),
2163
frozenset((token_month, token_end)))
2164
token_week = Token(re.compile(r"(\d+)W"),
2165
datetime.timedelta(weeks=1),
2166
frozenset((token_end,)))
2167
token_duration = Token(re.compile(r"P"), None,
2168
frozenset((token_year, token_month,
2169
token_day, token_time,
2171
# Define starting values
2172
value = datetime.timedelta() # Value so far
2174
followers = frozenset(token_duration,) # Following valid tokens
2175
s = duration # String left to parse
2176
# Loop until end token is found
2177
while found_token is not token_end:
2178
# Search for any currently valid tokens
2179
for token in followers:
2180
match = token.regexp.match(s)
2181
if match is not None:
2183
if token.value is not None:
2184
# Value found, parse digits
2185
factor = int(match.group(1), 10)
2186
# Add to value so far
2187
value += factor * token.value
2188
# Strip token from string
2189
s = token.regexp.sub("", s, 1)
2192
# Set valid next tokens
2193
followers = found_token.followers
2196
# No currently valid tokens were found
2197
raise ValueError("Invalid RFC 3339 duration")
2202
2075
def string_to_delta(interval):
2203
2076
"""Parse a string and return a datetime.timedelta
2348
2208
# Convert the SafeConfigParser object to a dict
2349
2209
server_settings = server_config.defaults()
2350
2210
# Use the appropriate methods on the non-string config options
2351
for option in ("debug", "use_dbus", "use_ipv6", "foreground"):
2211
for option in ("debug", "use_dbus", "use_ipv6"):
2352
2212
server_settings[option] = server_config.getboolean("DEFAULT",
2354
2214
if server_settings["port"]:
2355
2215
server_settings["port"] = server_config.getint("DEFAULT",
2357
if server_settings["socket"]:
2358
server_settings["socket"] = server_config.getint("DEFAULT",
2360
# Later, stdin will, and stdout and stderr might, be dup'ed
2361
# over with an opened os.devnull. But we don't want this to
2362
# happen with a supplied network socket.
2363
if 0 <= server_settings["socket"] <= 2:
2364
server_settings["socket"] = os.dup(server_settings
2366
2217
del server_config
2368
2219
# Override the settings from the config file with command line
2733
2578
del client_settings[client.name]["secret"]
2736
with (tempfile.NamedTemporaryFile
2737
(mode='wb', suffix=".pickle", prefix='clients-',
2738
dir=os.path.dirname(stored_state_path),
2739
delete=False)) as stored_state:
2581
tempfd, tempname = tempfile.mkstemp(suffix=".pickle",
2584
(stored_state_path))
2585
with os.fdopen(tempfd, "wb") as stored_state:
2740
2586
pickle.dump((clients, client_settings), stored_state)
2741
tempname=stored_state.name
2742
2587
os.rename(tempname, stored_state_path)
2743
2588
except (IOError, OSError) as e: