431
431
"created", "enabled", "fingerprint",
432
432
"host", "interval", "last_checked_ok",
433
433
"last_enabled", "name", "timeout")
434
client_defaults = { "timeout": "5m",
435
"extended_timeout": "15m",
437
"checker": "fping -q -- %%(host)s",
439
"approval_delay": "0s",
440
"approval_duration": "1s",
441
"approved_by_default": "True",
435
445
def timeout_milliseconds(self):
436
446
"Return the 'timeout' attribute in milliseconds"
437
return _timedelta_to_milliseconds(self.timeout)
447
return timedelta_to_milliseconds(self.timeout)
439
449
def extended_timeout_milliseconds(self):
440
450
"Return the 'extended_timeout' attribute in milliseconds"
441
return _timedelta_to_milliseconds(self.extended_timeout)
451
return timedelta_to_milliseconds(self.extended_timeout)
443
453
def interval_milliseconds(self):
444
454
"Return the 'interval' attribute in milliseconds"
445
return _timedelta_to_milliseconds(self.interval)
455
return timedelta_to_milliseconds(self.interval)
447
457
def approval_delay_milliseconds(self):
448
return _timedelta_to_milliseconds(self.approval_delay)
450
def __init__(self, name = None, config=None):
458
return timedelta_to_milliseconds(self.approval_delay)
461
def config_parser(config):
462
""" Construct a new dict of client settings of this form:
463
{ client_name: {setting_name: value, ...}, ...}
464
with exceptions for any special settings as defined above"""
466
for client_name in config.sections():
467
section = dict(config.items(client_name))
468
client = settings[client_name] = {}
470
client["host"] = section["host"]
471
# Reformat values from string types to Python types
472
client["approved_by_default"] = config.getboolean(
473
client_name, "approved_by_default")
474
client["enabled"] = config.getboolean(client_name, "enabled")
476
client["fingerprint"] = (section["fingerprint"].upper()
478
if "secret" in section:
479
client["secret"] = section["secret"].decode("base64")
480
elif "secfile" in section:
481
with open(os.path.expanduser(os.path.expandvars
482
(section["secfile"])),
484
client["secret"] = secfile.read()
486
raise TypeError("No secret or secfile for section %s"
488
client["timeout"] = string_to_delta(section["timeout"])
489
client["extended_timeout"] = string_to_delta(
490
section["extended_timeout"])
491
client["interval"] = string_to_delta(section["interval"])
492
client["approval_delay"] = string_to_delta(
493
section["approval_delay"])
494
client["approval_duration"] = string_to_delta(
495
section["approval_duration"])
496
client["checker_command"] = section["checker"]
497
client["last_approval_request"] = None
498
client["last_checked_ok"] = None
499
client["last_checker_status"] = None
500
if client["enabled"]:
501
client["last_enabled"] = datetime.datetime.utcnow()
502
client["expires"] = (datetime.datetime.utcnow()
505
client["last_enabled"] = None
506
client["expires"] = None
511
def __init__(self, settings, name = None):
451
512
"""Note: the 'checker' key in 'config' sets the
452
513
'checker_command' attribute and *not* the 'checker'
516
# adding all client settings
517
for setting, value in settings.iteritems():
518
setattr(self, setting, value)
457
520
logger.debug("Creating client %r", self.name)
458
521
# Uppercase and remove spaces from fingerprint for later
459
522
# comparison purposes with return value from the fingerprint()
461
self.fingerprint = (config["fingerprint"].upper()
463
524
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()
477
self.last_approval_request = None
478
self.last_enabled = datetime.datetime.utcnow()
479
self.last_checked_ok = None
480
self.last_checker_status = None
481
self.timeout = string_to_delta(config["timeout"])
482
self.extended_timeout = string_to_delta(config
483
["extended_timeout"])
484
self.interval = string_to_delta(config["interval"])
525
self.created = settings.get("created", datetime.datetime.utcnow())
527
# attributes specific for this server instance
485
528
self.checker = None
486
529
self.checker_initiator_tag = None
487
530
self.disable_initiator_tag = None
488
self.expires = datetime.datetime.utcnow() + self.timeout
489
531
self.checker_callback_tag = None
490
self.checker_command = config["checker"]
491
532
self.current_checker_command = None
492
self._approved = None
493
self.approved_by_default = config.get("approved_by_default",
495
534
self.approvals_pending = 0
496
self.approval_delay = string_to_delta(
497
config["approval_delay"])
498
self.approval_duration = string_to_delta(
499
config["approval_duration"])
500
535
self.changedstate = (multiprocessing_manager
501
536
.Condition(multiprocessing_manager
1062
1098
datetime_to_dbus, "LastApprovalRequest")
1063
1099
approved_by_default = notifychangeproperty(dbus.Boolean,
1064
1100
"ApprovedByDefault")
1065
approval_delay = notifychangeproperty(dbus.UInt16,
1101
approval_delay = notifychangeproperty(dbus.UInt64,
1066
1102
"ApprovalDelay",
1068
_timedelta_to_milliseconds)
1104
timedelta_to_milliseconds)
1069
1105
approval_duration = notifychangeproperty(
1070
dbus.UInt16, "ApprovalDuration",
1071
type_func = _timedelta_to_milliseconds)
1106
dbus.UInt64, "ApprovalDuration",
1107
type_func = timedelta_to_milliseconds)
1072
1108
host = notifychangeproperty(dbus.String, "Host")
1073
timeout = notifychangeproperty(dbus.UInt16, "Timeout",
1109
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1075
_timedelta_to_milliseconds)
1111
timedelta_to_milliseconds)
1076
1112
extended_timeout = notifychangeproperty(
1077
dbus.UInt16, "ExtendedTimeout",
1078
type_func = _timedelta_to_milliseconds)
1079
interval = notifychangeproperty(dbus.UInt16,
1113
dbus.UInt64, "ExtendedTimeout",
1114
type_func = timedelta_to_milliseconds)
1115
interval = notifychangeproperty(dbus.UInt64,
1082
_timedelta_to_milliseconds)
1118
timedelta_to_milliseconds)
1083
1119
checker_command = notifychangeproperty(dbus.String, "Checker")
1085
1121
del notifychangeproperty
2217
2235
if (name != "secret" and
2218
2236
value != old_client_settings[client_name]
2220
setattr(client, name, value)
2238
client[name] = value
2221
2239
except KeyError:
2224
2242
# Clients who has passed its expire date can still be
2225
# enabled if its last checker was sucessful. Clients
2243
# enabled if its last checker was successful. Clients
2226
2244
# whose checker failed before we stored its state is
2227
2245
# assumed to have failed all checkers during downtime.
2228
if client["enabled"] and client["last_checked_ok"]:
2229
if ((datetime.datetime.utcnow()
2230
- client["last_checked_ok"])
2231
> client["interval"]):
2232
if client["last_checker_status"] != 0:
2246
if client["enabled"]:
2247
if datetime.datetime.utcnow() >= client["expires"]:
2248
if not client["last_checked_ok"]:
2250
"disabling client {0} - Client never "
2251
"performed a successfull checker"
2252
.format(client["name"]))
2253
client["enabled"] = False
2254
elif client["last_checker_status"] != 0:
2256
"disabling client {0} - Client "
2257
"last checker failed with error code {1}"
2258
.format(client["name"],
2259
client["last_checker_status"]))
2233
2260
client["enabled"] = False
2235
2262
client["expires"] = (datetime.datetime
2237
2264
+ client["timeout"])
2239
client["changedstate"] = (multiprocessing_manager
2241
(multiprocessing_manager
2244
new_client = (ClientDBusTransitional.__new__
2245
(ClientDBusTransitional))
2246
tcp_server.clients[client_name] = new_client
2247
new_client.bus = bus
2248
for name, value in client.iteritems():
2249
setattr(new_client, name, value)
2250
client_object_name = unicode(client_name).translate(
2251
{ord("."): ord("_"),
2252
ord("-"): ord("_")})
2253
new_client.dbus_object_path = (dbus.ObjectPath
2255
+ client_object_name))
2256
DBusObjectWithProperties.__init__(new_client,
2261
tcp_server.clients[client_name] = (Client.__new__
2263
for name, value in client.iteritems():
2264
setattr(tcp_server.clients[client_name],
2268
tcp_server.clients[client_name].secret = (
2269
crypt.decrypt(tcp_server.clients[client_name]
2271
client_settings[client_name]
2267
client["secret"] = (
2268
pgp.decrypt(client["encrypted_secret"],
2269
client_settings[client_name]
2274
2272
# If decryption fails, we use secret from new settings
2275
tcp_server.clients[client_name].secret = (
2273
logger.debug("Failed to decrypt {0} old secret"
2274
.format(client_name))
2275
client["secret"] = (
2276
2276
client_settings[client_name]["secret"])
2278
# Create/remove clients based on new changes made to config
2279
for clientname in set(old_client_settings) - set(client_settings):
2280
del tcp_server.clients[clientname]
2281
for clientname in set(client_settings) - set(old_client_settings):
2282
tcp_server.clients[clientname] = (client_class(name
2279
# Add/remove clients based on new changes made to config
2280
for client_name in set(old_client_settings) - set(client_settings):
2281
del clients_data[client_name]
2282
for client_name in set(client_settings) - set(old_client_settings):
2283
clients_data[client_name] = client_settings[client_name]
2285
# Create clients all clients
2286
for client_name, client in clients_data.iteritems():
2287
tcp_server.clients[client_name] = client_class(
2288
name = client_name, settings = client)
2288
2290
if not tcp_server.clients:
2289
2291
logger.warning("No clients defined")
2397
2399
if attr not in exclude:
2398
2400
client_dict[attr] = getattr(client, attr)
2400
clients.append(client_dict)
2402
clients[client.name] = client_dict
2401
2403
del client_settings[client.name]["secret"]
2404
with os.fdopen(os.open(stored_state_path,
2405
os.O_CREAT|os.O_WRONLY|os.O_TRUNC,
2406
0600), "wb") as stored_state:
2406
tempfd, tempname = tempfile.mkstemp(suffix=".pickle",
2409
(stored_state_path))
2410
with os.fdopen(tempfd, "wb") as stored_state:
2407
2411
pickle.dump((clients, client_settings), stored_state)
2412
os.rename(tempname, stored_state_path)
2408
2413
except (IOError, OSError) as e:
2409
2414
logger.warning("Could not save persistent state: {0}"
2411
if e.errno not in (errno.ENOENT, errno.EACCES):
2421
if e.errno not in set((errno.ENOENT, errno.EACCES,
2414
2425
# Delete all clients, and settings from config
2415
2426
while tcp_server.clients: