431
430
"created", "enabled", "fingerprint",
432
431
"host", "interval", "last_checked_ok",
433
432
"last_enabled", "name", "timeout")
433
client_defaults = { "timeout": "5m",
434
"extended_timeout": "15m",
436
"checker": "fping -q -- %%(host)s",
438
"approval_delay": "0s",
439
"approval_duration": "1s",
440
"approved_by_default": "True",
435
444
def timeout_milliseconds(self):
436
445
"Return the 'timeout' attribute in milliseconds"
447
456
def approval_delay_milliseconds(self):
448
457
return timedelta_to_milliseconds(self.approval_delay)
450
def __init__(self, name = None, config=None):
460
def config_parser(config):
461
""" Construct a new dict of client settings of this form:
462
{ client_name: {setting_name: value, ...}, ...}
463
with exceptions for any special settings as defined above"""
465
for client_name in config.sections():
466
section = dict(config.items(client_name))
467
client = settings[client_name] = {}
469
client["host"] = section["host"]
470
# Reformat values from string types to Python types
471
client["approved_by_default"] = config.getboolean(
472
client_name, "approved_by_default")
473
client["enabled"] = config.getboolean(client_name, "enabled")
475
client["fingerprint"] = (section["fingerprint"].upper()
477
if "secret" in section:
478
client["secret"] = section["secret"].decode("base64")
479
elif "secfile" in section:
480
with open(os.path.expanduser(os.path.expandvars
481
(section["secfile"])),
483
client["secret"] = secfile.read()
485
raise TypeError("No secret or secfile for section %s"
487
client["timeout"] = string_to_delta(section["timeout"])
488
client["extended_timeout"] = string_to_delta(
489
section["extended_timeout"])
490
client["interval"] = string_to_delta(section["interval"])
491
client["approval_delay"] = string_to_delta(
492
section["approval_delay"])
493
client["approval_duration"] = string_to_delta(
494
section["approval_duration"])
495
client["checker_command"] = section["checker"]
496
client["last_approval_request"] = None
497
client["last_checked_ok"] = None
498
client["last_checker_status"] = None
499
if client["enabled"]:
500
client["last_enabled"] = datetime.datetime.utcnow()
501
client["expires"] = (datetime.datetime.utcnow()
504
client["last_enabled"] = None
505
client["expires"] = None
510
def __init__(self, settings, name = None):
451
511
"""Note: the 'checker' key in 'config' sets the
452
512
'checker_command' attribute and *not* the 'checker'
515
# adding all client settings
516
for setting, value in settings.iteritems():
517
setattr(self, setting, value)
457
519
logger.debug("Creating client %r", self.name)
458
520
# Uppercase and remove spaces from fingerprint for later
459
521
# comparison purposes with return value from the fingerprint()
461
self.fingerprint = (config["fingerprint"].upper()
463
523
logger.debug(" Fingerprint: %s", self.fingerprint)
464
if "secret" in config:
465
self.secret = config["secret"].decode("base64")
466
elif "secfile" in config:
467
with open(os.path.expanduser(os.path.expandvars
468
(config["secfile"])),
470
self.secret = secfile.read()
472
raise TypeError("No secret or secfile for client %s"
474
self.host = config.get("host", "")
475
self.created = datetime.datetime.utcnow()
476
self.enabled = config.get("enabled", True)
477
self.last_approval_request = None
479
self.last_enabled = datetime.datetime.utcnow()
481
self.last_enabled = None
482
self.last_checked_ok = None
483
self.last_checker_status = None
484
self.timeout = string_to_delta(config["timeout"])
485
self.extended_timeout = string_to_delta(config
486
["extended_timeout"])
487
self.interval = string_to_delta(config["interval"])
524
self.created = settings.get("created", datetime.datetime.utcnow())
526
# attributes specific for this server instance
488
527
self.checker = None
489
528
self.checker_initiator_tag = None
490
529
self.disable_initiator_tag = None
492
self.expires = datetime.datetime.utcnow() + self.timeout
495
530
self.checker_callback_tag = None
496
self.checker_command = config["checker"]
497
531
self.current_checker_command = None
498
532
self.approved = None
499
self.approved_by_default = config.get("approved_by_default",
501
533
self.approvals_pending = 0
502
self.approval_delay = string_to_delta(
503
config["approval_delay"])
504
self.approval_duration = string_to_delta(
505
config["approval_duration"])
506
534
self.changedstate = (multiprocessing_manager
507
535
.Condition(multiprocessing_manager
1068
1097
datetime_to_dbus, "LastApprovalRequest")
1069
1098
approved_by_default = notifychangeproperty(dbus.Boolean,
1070
1099
"ApprovedByDefault")
1071
approval_delay = notifychangeproperty(dbus.UInt16,
1100
approval_delay = notifychangeproperty(dbus.UInt64,
1072
1101
"ApprovalDelay",
1074
1103
timedelta_to_milliseconds)
1075
1104
approval_duration = notifychangeproperty(
1076
dbus.UInt16, "ApprovalDuration",
1105
dbus.UInt64, "ApprovalDuration",
1077
1106
type_func = timedelta_to_milliseconds)
1078
1107
host = notifychangeproperty(dbus.String, "Host")
1079
timeout = notifychangeproperty(dbus.UInt16, "Timeout",
1108
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1081
1110
timedelta_to_milliseconds)
1082
1111
extended_timeout = notifychangeproperty(
1083
dbus.UInt16, "ExtendedTimeout",
1112
dbus.UInt64, "ExtendedTimeout",
1084
1113
type_func = timedelta_to_milliseconds)
1085
interval = notifychangeproperty(dbus.UInt16,
1114
interval = notifychangeproperty(dbus.UInt64,
1088
1117
timedelta_to_milliseconds)
2179
2200
client_class = functools.partial(ClientDBusTransitional,
2182
special_settings = {
2183
# Some settings need to be accessd by special methods;
2184
# booleans need .getboolean(), etc. Here is a list of them:
2185
"approved_by_default":
2187
client_config.getboolean(section, "approved_by_default"),
2190
client_config.getboolean(section, "enabled"),
2192
# Construct a new dict of client settings of this form:
2193
# { client_name: {setting_name: value, ...}, ...}
2194
# with exceptions for any special settings as defined above
2195
client_settings = dict((clientname,
2198
if setting not in special_settings
2199
else special_settings[setting]
2201
for setting, value in
2202
client_config.items(clientname)))
2203
for clientname in client_config.sections())
2203
client_settings = Client.config_parser(client_config)
2205
2204
old_client_settings = {}
2208
2207
# Get client data and settings from last running state.
2209
2208
if server_settings["restore"]:
2235
2232
if (name != "secret" and
2236
2233
value != old_client_settings[client_name]
2238
setattr(client, name, value)
2235
client[name] = value
2239
2236
except KeyError:
2242
2239
# Clients who has passed its expire date can still be
2243
# enabled if its last checker was sucessful. Clients
2240
# enabled if its last checker was successful. Clients
2244
2241
# whose checker failed before we stored its state is
2245
2242
# assumed to have failed all checkers during downtime.
2246
if client["enabled"] and client["last_checked_ok"]:
2247
if ((datetime.datetime.utcnow()
2248
- client["last_checked_ok"])
2249
> client["interval"]):
2250
if client["last_checker_status"] != 0:
2243
if client["enabled"]:
2244
if datetime.datetime.utcnow() >= client["expires"]:
2245
if not client["last_checked_ok"]:
2247
"disabling client {0} - Client never "
2248
"performed a successfull checker"
2249
.format(client["name"]))
2250
client["enabled"] = False
2251
elif client["last_checker_status"] != 0:
2253
"disabling client {0} - Client "
2254
"last checker failed with error code {1}"
2255
.format(client["name"],
2256
client["last_checker_status"]))
2251
2257
client["enabled"] = False
2253
2259
client["expires"] = (datetime.datetime
2255
2261
+ client["timeout"])
2257
client["changedstate"] = (multiprocessing_manager
2259
(multiprocessing_manager
2262
new_client = (ClientDBusTransitional.__new__
2263
(ClientDBusTransitional))
2264
tcp_server.clients[client_name] = new_client
2265
new_client.bus = bus
2266
for name, value in client.iteritems():
2267
setattr(new_client, name, value)
2268
client_object_name = unicode(client_name).translate(
2269
{ord("."): ord("_"),
2270
ord("-"): ord("_")})
2271
new_client.dbus_object_path = (dbus.ObjectPath
2273
+ client_object_name))
2274
DBusObjectWithProperties.__init__(new_client,
2279
tcp_server.clients[client_name] = (Client.__new__
2281
for name, value in client.iteritems():
2282
setattr(tcp_server.clients[client_name],
2286
tcp_server.clients[client_name].secret = (
2287
crypt.decrypt(tcp_server.clients[client_name]
2289
client_settings[client_name]
2264
client["secret"] = (
2265
pgp.decrypt(client["encrypted_secret"],
2266
client_settings[client_name]
2292
2269
# If decryption fails, we use secret from new settings
2293
tcp_server.clients[client_name].secret = (
2270
logger.debug("Failed to decrypt {0} old secret"
2271
.format(client_name))
2272
client["secret"] = (
2294
2273
client_settings[client_name]["secret"])
2296
# Create/remove clients based on new changes made to config
2297
for clientname in set(old_client_settings) - set(client_settings):
2298
del tcp_server.clients[clientname]
2299
for clientname in set(client_settings) - set(old_client_settings):
2300
tcp_server.clients[clientname] = (client_class(name
2276
# Add/remove clients based on new changes made to config
2277
for client_name in set(old_client_settings) - set(client_settings):
2278
del clients_data[client_name]
2279
for client_name in set(client_settings) - set(old_client_settings):
2280
clients_data[client_name] = client_settings[client_name]
2282
# Create clients all clients
2283
for client_name, client in clients_data.iteritems():
2284
tcp_server.clients[client_name] = client_class(
2285
name = client_name, settings = client)
2306
2287
if not tcp_server.clients:
2307
2288
logger.warning("No clients defined")
2394
2374
# Store client before exiting. Secrets are encrypted with key
2395
2375
# based on what config file has. If config file is
2396
2376
# removed/edited, old secret will thus be unrecovable.
2398
with Crypto() as crypt:
2378
with PGPEngine() as pgp:
2399
2379
for client in tcp_server.clients.itervalues():
2400
2380
key = client_settings[client.name]["secret"]
2401
client.encrypted_secret = crypt.encrypt(client.secret,
2381
client.encrypted_secret = pgp.encrypt(client.secret,
2403
2383
client_dict = {}
2405
# A list of attributes that will not be stored when
2407
exclude = set(("bus", "changedstate", "secret"))
2385
# A list of attributes that can not be pickled
2387
exclude = set(("bus", "changedstate", "secret",
2408
2389
for name, typ in (inspect.getmembers
2409
2390
(dbus.service.Object)):
2410
2391
exclude.add(name)