395
395
logger.error(bad_states[state] + ": %r", error)
397
397
elif state == avahi.SERVER_RUNNING:
400
except dbus.exceptions.DBusException as error:
401
if (error.get_dbus_name()
402
== "org.freedesktop.Avahi.CollisionError"):
403
logger.info("Local Zeroconf service name"
405
return self.rename(remove=False)
407
logger.critical("D-Bus Exception", exc_info=error)
411
400
if error is None:
412
401
logger.debug("Unknown state: %r", state)
435
424
.format(self.name)))
438
def call_pipe(connection, # : multiprocessing.Connection
439
func, *args, **kwargs):
440
"""This function is meant to be called by multiprocessing.Process
442
This function runs func(*args, **kwargs), and writes the resulting
443
return value on the provided multiprocessing.Connection.
445
connection.send(func(*args, **kwargs))
448
428
class Client(object):
449
429
"""A representation of a client host served by this server.
476
456
last_checker_status: integer between 0 and 255 reflecting exit
477
457
status of last checker. -1 reflects crashed
478
458
checker, -2 means no checker completed yet.
479
last_checker_signal: The signal which killed the last checker, if
480
last_checker_status is -1
481
459
last_enabled: datetime.datetime(); (UTC) or None
482
460
name: string; from the config file, used in log messages and
483
461
D-Bus identifiers
657
635
# Also start a new checker *right now*.
658
636
self.start_checker()
660
def checker_callback(self, source, condition, connection,
638
def checker_callback(self, pid, condition, command):
662
639
"""The checker has completed, so take appropriate actions."""
663
640
self.checker_callback_tag = None
664
641
self.checker = None
665
# Read return code from connection (see call_pipe)
666
returncode = connection.recv()
670
self.last_checker_status = returncode
671
self.last_checker_signal = None
642
if os.WIFEXITED(condition):
643
self.last_checker_status = os.WEXITSTATUS(condition)
672
644
if self.last_checker_status == 0:
673
645
logger.info("Checker for %(name)s succeeded",
677
649
logger.info("Checker for %(name)s failed", vars(self))
679
651
self.last_checker_status = -1
680
self.last_checker_signal = -returncode
681
652
logger.warning("Checker for %(name)s crashed?",
685
655
def checked_ok(self):
686
656
"""Assert that the client has been seen, alive and well."""
687
657
self.last_checked_ok = datetime.datetime.utcnow()
688
658
self.last_checker_status = 0
689
self.last_checker_signal = None
690
659
self.bump_timeout()
692
661
def bump_timeout(self, timeout=None):
718
687
# than 'timeout' for the client to be disabled, which is as it
721
if self.checker is not None and not self.checker.is_alive():
722
logger.warning("Checker was not alive; joining")
690
# If a checker exists, make sure it is not a zombie
692
pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
693
except AttributeError:
695
except OSError as error:
696
if error.errno != errno.ECHILD:
700
logger.warning("Checker was a zombie")
701
gobject.source_remove(self.checker_callback_tag)
702
self.checker_callback(pid, status,
703
self.current_checker_command)
725
704
# Start a new checker if needed
726
705
if self.checker is None:
727
706
# Escape attributes for the shell
737
716
return True # Try again later
738
717
self.current_checker_command = command
739
logger.info("Starting checker %r for %s", command,
741
# We don't need to redirect stdout and stderr, since
742
# in normal mode, that is already done by daemon(),
743
# and in debug mode we don't want to. (Stdin is
744
# always replaced by /dev/null.)
745
# The exception is when not debugging but nevertheless
746
# running in the foreground; use the previously
748
popen_args = { "close_fds": True,
751
if (not self.server_settings["debug"]
752
and self.server_settings["foreground"]):
753
popen_args.update({"stdout": wnull,
755
pipe = multiprocessing.Pipe(duplex = False)
756
self.checker = multiprocessing.Process(
758
args = (pipe[1], subprocess.call, command),
761
self.checker_callback_tag = gobject.io_add_watch(
762
pipe[0].fileno(), gobject.IO_IN,
763
self.checker_callback, pipe[0], command)
719
logger.info("Starting checker %r for %s", command,
721
# We don't need to redirect stdout and stderr, since
722
# in normal mode, that is already done by daemon(),
723
# and in debug mode we don't want to. (Stdin is
724
# always replaced by /dev/null.)
725
# The exception is when not debugging but nevertheless
726
# running in the foreground; use the previously
729
if (not self.server_settings["debug"]
730
and self.server_settings["foreground"]):
731
popen_args.update({"stdout": wnull,
733
self.checker = subprocess.Popen(command,
738
except OSError as error:
739
logger.error("Failed to start subprocess",
742
self.checker_callback_tag = gobject.child_watch_add(
743
self.checker.pid, self.checker_callback, data=command)
744
# The checker may have completed before the gobject
745
# watch was added. Check for this.
747
pid, status = os.waitpid(self.checker.pid, os.WNOHANG)
748
except OSError as error:
749
if error.errno == errno.ECHILD:
750
# This should never happen
751
logger.error("Child process vanished",
756
gobject.source_remove(self.checker_callback_tag)
757
self.checker_callback(pid, status, command)
764
758
# Re-run this periodically if run by gobject.timeout_add
1122
1123
# Create a new, but exactly alike, function
1123
1124
# object, and decorate it to be a new D-Bus signal
1124
1125
# with the alternate D-Bus interface name
1125
if sys.version_info.major == 2:
1126
if sys.version == 2:
1126
1127
new_function = types.FunctionType(
1127
1128
nonmethod_func.func_code,
1128
1129
nonmethod_func.func_globals,
1367
1368
DBusObjectWithProperties.__del__(self, *args, **kwargs)
1368
1369
Client.__del__(self, *args, **kwargs)
1370
def checker_callback(self, source, condition,
1371
connection, command, *args, **kwargs):
1372
ret = Client.checker_callback(self, source, condition,
1373
connection, command, *args,
1375
exitstatus = self.last_checker_status
1371
def checker_callback(self, pid, condition, command,
1373
self.checker_callback_tag = None
1375
if os.WIFEXITED(condition):
1376
exitstatus = os.WEXITSTATUS(condition)
1377
1377
# Emit D-Bus signal
1378
1378
self.CheckerCompleted(dbus.Int16(exitstatus),
1379
dbus.Int64(condition),
1380
1380
dbus.String(command))
1382
1382
# Emit D-Bus signal
1383
1383
self.CheckerCompleted(dbus.Int16(-1),
1385
self.last_checker_signal),
1384
dbus.Int64(condition),
1386
1385
dbus.String(command))
1387
return Client.checker_callback(self, pid, condition, command,
1389
1390
def start_checker(self, *args, **kwargs):
1390
1391
old_checker_pid = getattr(self.checker, "pid", None)