431
432
"created", "enabled", "fingerprint",
432
433
"host", "interval", "last_checked_ok",
433
434
"last_enabled", "name", "timeout")
435
client_defaults = { "timeout": "5m",
436
"extended_timeout": "15m",
438
"checker": "fping -q -- %%(host)s",
440
"approval_delay": "0s",
441
"approval_duration": "1s",
442
"approved_by_default": "True",
435
446
def timeout_milliseconds(self):
436
447
"Return the 'timeout' attribute in milliseconds"
437
return _timedelta_to_milliseconds(self.timeout)
448
return timedelta_to_milliseconds(self.timeout)
439
450
def extended_timeout_milliseconds(self):
440
451
"Return the 'extended_timeout' attribute in milliseconds"
441
return _timedelta_to_milliseconds(self.extended_timeout)
452
return timedelta_to_milliseconds(self.extended_timeout)
443
454
def interval_milliseconds(self):
444
455
"Return the 'interval' attribute in milliseconds"
445
return _timedelta_to_milliseconds(self.interval)
456
return timedelta_to_milliseconds(self.interval)
447
458
def approval_delay_milliseconds(self):
448
return _timedelta_to_milliseconds(self.approval_delay)
450
def __init__(self, name = None, config=None):
459
return timedelta_to_milliseconds(self.approval_delay)
462
def config_parser(config):
463
"""Construct a new dict of client settings of this form:
464
{ client_name: {setting_name: value, ...}, ...}
465
with exceptions for any special settings as defined above.
466
NOTE: Must be a pure function. Must return the same result
467
value given the same arguments.
470
for client_name in config.sections():
471
section = dict(config.items(client_name))
472
client = settings[client_name] = {}
474
client["host"] = section["host"]
475
# Reformat values from string types to Python types
476
client["approved_by_default"] = config.getboolean(
477
client_name, "approved_by_default")
478
client["enabled"] = config.getboolean(client_name,
481
client["fingerprint"] = (section["fingerprint"].upper()
483
if "secret" in section:
484
client["secret"] = section["secret"].decode("base64")
485
elif "secfile" in section:
486
with open(os.path.expanduser(os.path.expandvars
487
(section["secfile"])),
489
client["secret"] = secfile.read()
491
raise TypeError("No secret or secfile for section %s"
493
client["timeout"] = string_to_delta(section["timeout"])
494
client["extended_timeout"] = string_to_delta(
495
section["extended_timeout"])
496
client["interval"] = string_to_delta(section["interval"])
497
client["approval_delay"] = string_to_delta(
498
section["approval_delay"])
499
client["approval_duration"] = string_to_delta(
500
section["approval_duration"])
501
client["checker_command"] = section["checker"]
502
client["last_approval_request"] = None
503
client["last_checked_ok"] = None
504
client["last_checker_status"] = None
509
def __init__(self, settings, name = None):
451
510
"""Note: the 'checker' key in 'config' sets the
452
511
'checker_command' attribute and *not* the 'checker'
514
# adding all client settings
515
for setting, value in settings.iteritems():
516
setattr(self, setting, value)
519
if not hasattr(self, "last_enabled"):
520
self.last_enabled = datetime.datetime.utcnow()
521
if not hasattr(self, "expires"):
522
self.expires = (datetime.datetime.utcnow()
525
self.last_enabled = None
457
528
logger.debug("Creating client %r", self.name)
458
529
# Uppercase and remove spaces from fingerprint for later
459
530
# comparison purposes with return value from the fingerprint()
461
self.fingerprint = (config["fingerprint"].upper()
463
532
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"])
533
self.created = settings.get("created",
534
datetime.datetime.utcnow())
536
# attributes specific for this server instance
485
537
self.checker = None
486
538
self.checker_initiator_tag = None
487
539
self.disable_initiator_tag = None
488
self.expires = datetime.datetime.utcnow() + self.timeout
489
540
self.checker_callback_tag = None
490
self.checker_command = config["checker"]
491
541
self.current_checker_command = None
492
self._approved = None
493
self.approved_by_default = config.get("approved_by_default",
495
543
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
544
self.changedstate = (multiprocessing_manager
501
545
.Condition(multiprocessing_manager
1062
1107
datetime_to_dbus, "LastApprovalRequest")
1063
1108
approved_by_default = notifychangeproperty(dbus.Boolean,
1064
1109
"ApprovedByDefault")
1065
approval_delay = notifychangeproperty(dbus.UInt16,
1110
approval_delay = notifychangeproperty(dbus.UInt64,
1066
1111
"ApprovalDelay",
1068
_timedelta_to_milliseconds)
1113
timedelta_to_milliseconds)
1069
1114
approval_duration = notifychangeproperty(
1070
dbus.UInt16, "ApprovalDuration",
1071
type_func = _timedelta_to_milliseconds)
1115
dbus.UInt64, "ApprovalDuration",
1116
type_func = timedelta_to_milliseconds)
1072
1117
host = notifychangeproperty(dbus.String, "Host")
1073
timeout = notifychangeproperty(dbus.UInt16, "Timeout",
1118
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1075
_timedelta_to_milliseconds)
1120
timedelta_to_milliseconds)
1076
1121
extended_timeout = notifychangeproperty(
1077
dbus.UInt16, "ExtendedTimeout",
1078
type_func = _timedelta_to_milliseconds)
1079
interval = notifychangeproperty(dbus.UInt16,
1122
dbus.UInt64, "ExtendedTimeout",
1123
type_func = timedelta_to_milliseconds)
1124
interval = notifychangeproperty(dbus.UInt64,
1082
_timedelta_to_milliseconds)
1127
timedelta_to_milliseconds)
1083
1128
checker_command = notifychangeproperty(dbus.String, "Checker")
1085
1130
del notifychangeproperty
1322
1367
if value is None: # get
1323
1368
return dbus.UInt64(self.timeout_milliseconds())
1324
1369
self.timeout = datetime.timedelta(0, 0, 0, value)
1325
if getattr(self, "disable_initiator_tag", None) is None:
1327
1370
# Reschedule timeout
1328
gobject.source_remove(self.disable_initiator_tag)
1329
self.disable_initiator_tag = None
1331
time_to_die = _timedelta_to_milliseconds((self
1336
if time_to_die <= 0:
1337
# The timeout has passed
1340
self.expires = (datetime.datetime.utcnow()
1341
+ datetime.timedelta(milliseconds =
1343
self.disable_initiator_tag = (gobject.timeout_add
1344
(time_to_die, self.disable))
1372
now = datetime.datetime.utcnow()
1373
time_to_die = timedelta_to_milliseconds(
1374
(self.last_checked_ok + self.timeout) - now)
1375
if time_to_die <= 0:
1376
# The timeout has passed
1379
self.expires = (now +
1380
datetime.timedelta(milliseconds =
1382
if (getattr(self, "disable_initiator_tag", None)
1385
gobject.source_remove(self.disable_initiator_tag)
1386
self.disable_initiator_tag = (gobject.timeout_add
1346
1390
# ExtendedTimeout - property
1347
1391
@dbus_service_property(_interface, signature="t",
2224
2244
if (name != "secret" and
2225
2245
value != old_client_settings[client_name]
2227
setattr(client, name, value)
2247
client[name] = value
2228
2248
except KeyError:
2231
2251
# Clients who has passed its expire date can still be
2232
# enabled if its last checker was sucessful. Clients
2252
# enabled if its last checker was successful. Clients
2233
2253
# whose checker failed before we stored its state is
2234
2254
# assumed to have failed all checkers during downtime.
2235
if client["enabled"] and client["last_checked_ok"]:
2236
if ((datetime.datetime.utcnow()
2237
- client["last_checked_ok"])
2238
> client["interval"]):
2239
if client["last_checker_status"] != 0:
2255
if client["enabled"]:
2256
if datetime.datetime.utcnow() >= client["expires"]:
2257
if not client["last_checked_ok"]:
2259
"disabling client {0} - Client never "
2260
"performed a successfull checker"
2261
.format(client["name"]))
2262
client["enabled"] = False
2263
elif client["last_checker_status"] != 0:
2265
"disabling client {0} - Client "
2266
"last checker failed with error code {1}"
2267
.format(client["name"],
2268
client["last_checker_status"]))
2240
2269
client["enabled"] = False
2242
2271
client["expires"] = (datetime.datetime
2244
2273
+ client["timeout"])
2246
client["changedstate"] = (multiprocessing_manager
2248
(multiprocessing_manager
2251
new_client = (ClientDBusTransitional.__new__
2252
(ClientDBusTransitional))
2253
tcp_server.clients[client_name] = new_client
2254
new_client.bus = bus
2255
for name, value in client.iteritems():
2256
setattr(new_client, name, value)
2257
client_object_name = unicode(client_name).translate(
2258
{ord("."): ord("_"),
2259
ord("-"): ord("_")})
2260
new_client.dbus_object_path = (dbus.ObjectPath
2262
+ client_object_name))
2263
DBusObjectWithProperties.__init__(new_client,
2268
tcp_server.clients[client_name] = (Client.__new__
2270
for name, value in client.iteritems():
2271
setattr(tcp_server.clients[client_name],
2274
logger.debug("Last checker succeeded,"
2275
" keeping {0} enabled"
2276
.format(client["name"]))
2275
tcp_server.clients[client_name].secret = (
2276
crypt.decrypt(tcp_server.clients[client_name]
2278
client_settings[client_name]
2278
client["secret"] = (
2279
pgp.decrypt(client["encrypted_secret"],
2280
client_settings[client_name]
2281
2283
# If decryption fails, we use secret from new settings
2282
tcp_server.clients[client_name].secret = (
2284
logger.debug("Failed to decrypt {0} old secret"
2285
.format(client_name))
2286
client["secret"] = (
2283
2287
client_settings[client_name]["secret"])
2285
# Create/remove clients based on new changes made to config
2286
for clientname in set(old_client_settings) - set(client_settings):
2287
del tcp_server.clients[clientname]
2288
for clientname in set(client_settings) - set(old_client_settings):
2289
tcp_server.clients[clientname] = (client_class(name
2290
# Add/remove clients based on new changes made to config
2291
for client_name in (set(old_client_settings)
2292
- set(client_settings)):
2293
del clients_data[client_name]
2294
for client_name in (set(client_settings)
2295
- set(old_client_settings)):
2296
clients_data[client_name] = client_settings[client_name]
2298
# Create clients all clients
2299
for client_name, client in clients_data.iteritems():
2300
tcp_server.clients[client_name] = client_class(
2301
name = client_name, settings = client)
2295
2303
if not tcp_server.clients:
2296
2304
logger.warning("No clients defined")
2404
2412
if attr not in exclude:
2405
2413
client_dict[attr] = getattr(client, attr)
2407
clients.append(client_dict)
2415
clients[client.name] = client_dict
2408
2416
del client_settings[client.name]["secret"]
2411
with os.fdopen(os.open(stored_state_path,
2412
os.O_CREAT|os.O_WRONLY|os.O_TRUNC,
2413
0600), "wb") as stored_state:
2419
tempfd, tempname = tempfile.mkstemp(suffix=".pickle",
2422
(stored_state_path))
2423
with os.fdopen(tempfd, "wb") as stored_state:
2414
2424
pickle.dump((clients, client_settings), stored_state)
2425
os.rename(tempname, stored_state_path)
2415
2426
except (IOError, OSError) as e:
2416
2427
logger.warning("Could not save persistent state: {0}"
2418
if e.errno not in (errno.ENOENT, errno.EACCES):
2434
if e.errno not in set((errno.ENOENT, errno.EACCES,
2421
2438
# Delete all clients, and settings from config
2422
2439
while tcp_server.clients: