432
431
"created", "enabled", "fingerprint",
433
432
"host", "interval", "last_checked_ok",
434
433
"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",
446
435
def timeout_milliseconds(self):
447
436
"Return the 'timeout' attribute in milliseconds"
448
return timedelta_to_milliseconds(self.timeout)
437
return _timedelta_to_milliseconds(self.timeout)
450
439
def extended_timeout_milliseconds(self):
451
440
"Return the 'extended_timeout' attribute in milliseconds"
452
return timedelta_to_milliseconds(self.extended_timeout)
441
return _timedelta_to_milliseconds(self.extended_timeout)
454
443
def interval_milliseconds(self):
455
444
"Return the 'interval' attribute in milliseconds"
456
return timedelta_to_milliseconds(self.interval)
445
return _timedelta_to_milliseconds(self.interval)
458
447
def approval_delay_milliseconds(self):
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):
448
return _timedelta_to_milliseconds(self.approval_delay)
450
def __init__(self, name = None, config=None):
510
451
"""Note: the 'checker' key in 'config' sets the
511
452
'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
528
457
logger.debug("Creating client %r", self.name)
529
458
# Uppercase and remove spaces from fingerprint for later
530
459
# comparison purposes with return value from the fingerprint()
461
self.fingerprint = (config["fingerprint"].upper()
532
463
logger.debug(" Fingerprint: %s", self.fingerprint)
533
self.created = settings.get("created",
534
datetime.datetime.utcnow())
536
# attributes specific for this server instance
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"])
537
488
self.checker = None
538
489
self.checker_initiator_tag = None
539
490
self.disable_initiator_tag = None
492
self.expires = datetime.datetime.utcnow() + self.timeout
540
495
self.checker_callback_tag = None
496
self.checker_command = config["checker"]
541
497
self.current_checker_command = None
498
self._approved = None
499
self.approved_by_default = config.get("approved_by_default",
543
501
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"])
544
506
self.changedstate = (multiprocessing_manager
545
507
.Condition(multiprocessing_manager
1104
1068
datetime_to_dbus, "LastApprovalRequest")
1105
1069
approved_by_default = notifychangeproperty(dbus.Boolean,
1106
1070
"ApprovedByDefault")
1107
approval_delay = notifychangeproperty(dbus.UInt64,
1071
approval_delay = notifychangeproperty(dbus.UInt16,
1108
1072
"ApprovalDelay",
1110
timedelta_to_milliseconds)
1074
_timedelta_to_milliseconds)
1111
1075
approval_duration = notifychangeproperty(
1112
dbus.UInt64, "ApprovalDuration",
1113
type_func = timedelta_to_milliseconds)
1076
dbus.UInt16, "ApprovalDuration",
1077
type_func = _timedelta_to_milliseconds)
1114
1078
host = notifychangeproperty(dbus.String, "Host")
1115
timeout = notifychangeproperty(dbus.UInt64, "Timeout",
1079
timeout = notifychangeproperty(dbus.UInt16, "Timeout",
1117
timedelta_to_milliseconds)
1081
_timedelta_to_milliseconds)
1118
1082
extended_timeout = notifychangeproperty(
1119
dbus.UInt64, "ExtendedTimeout",
1120
type_func = timedelta_to_milliseconds)
1121
interval = notifychangeproperty(dbus.UInt64,
1083
dbus.UInt16, "ExtendedTimeout",
1084
type_func = _timedelta_to_milliseconds)
1085
interval = notifychangeproperty(dbus.UInt16,
1124
timedelta_to_milliseconds)
1088
_timedelta_to_milliseconds)
1125
1089
checker_command = notifychangeproperty(dbus.String, "Checker")
1127
1091
del notifychangeproperty
1356
1328
if value is None: # get
1357
1329
return dbus.UInt64(self.timeout_milliseconds())
1358
1330
self.timeout = datetime.timedelta(0, 0, 0, value)
1331
if getattr(self, "disable_initiator_tag", None) is None:
1359
1333
# Reschedule timeout
1361
now = datetime.datetime.utcnow()
1362
time_to_die = timedelta_to_milliseconds(
1363
(self.last_checked_ok + self.timeout) - now)
1364
if time_to_die <= 0:
1365
# The timeout has passed
1368
self.expires = (now +
1369
datetime.timedelta(milliseconds =
1371
if (getattr(self, "disable_initiator_tag", None)
1374
gobject.source_remove(self.disable_initiator_tag)
1375
self.disable_initiator_tag = (gobject.timeout_add
1334
gobject.source_remove(self.disable_initiator_tag)
1335
self.disable_initiator_tag = None
1337
time_to_die = _timedelta_to_milliseconds((self
1342
if time_to_die <= 0:
1343
# The timeout has passed
1346
self.expires = (datetime.datetime.utcnow()
1347
+ datetime.timedelta(milliseconds =
1349
self.disable_initiator_tag = (gobject.timeout_add
1350
(time_to_die, self.disable))
1379
1352
# ExtendedTimeout - property
1380
1353
@dbus_service_property(_interface, signature="t",
2194
2178
client_class = functools.partial(ClientDBusTransitional,
2197
client_settings = Client.config_parser(client_config)
2181
special_settings = {
2182
# Some settings need to be accessd by special methods;
2183
# booleans need .getboolean(), etc. Here is a list of them:
2184
"approved_by_default":
2186
client_config.getboolean(section, "approved_by_default"),
2189
client_config.getboolean(section, "enabled"),
2191
# Construct a new dict of client settings of this form:
2192
# { client_name: {setting_name: value, ...}, ...}
2193
# with exceptions for any special settings as defined above
2194
client_settings = dict((clientname,
2197
if setting not in special_settings
2198
else special_settings[setting]
2200
for setting, value in
2201
client_config.items(clientname)))
2202
for clientname in client_config.sections())
2198
2204
old_client_settings = {}
2201
2207
# Get client data and settings from last running state.
2202
2208
if server_settings["restore"]:
2229
2234
if (name != "secret" and
2230
2235
value != old_client_settings[client_name]
2232
client[name] = value
2237
setattr(client, name, value)
2233
2238
except KeyError:
2236
2241
# Clients who has passed its expire date can still be
2237
# enabled if its last checker was successful. Clients
2238
# whose checker succeeded before we stored its state is
2239
# assumed to have successfully run all checkers during
2241
if client["enabled"]:
2242
if datetime.datetime.utcnow() >= client["expires"]:
2243
if not client["last_checked_ok"]:
2245
"disabling client {0} - Client never "
2246
"performed a successful checker"
2247
.format(client_name))
2248
client["enabled"] = False
2249
elif client["last_checker_status"] != 0:
2251
"disabling client {0} - Client "
2252
"last checker failed with error code {1}"
2253
.format(client_name,
2254
client["last_checker_status"]))
2242
# enabled if its last checker was sucessful. Clients
2243
# whose checker failed before we stored its state is
2244
# assumed to have failed all checkers during downtime.
2245
if client["enabled"] and client["last_checked_ok"]:
2246
if ((datetime.datetime.utcnow()
2247
- client["last_checked_ok"])
2248
> client["interval"]):
2249
if client["last_checker_status"] != 0:
2255
2250
client["enabled"] = False
2257
2252
client["expires"] = (datetime.datetime
2259
2254
+ client["timeout"])
2260
logger.debug("Last checker succeeded,"
2261
" keeping {0} enabled"
2262
.format(client_name))
2256
client["changedstate"] = (multiprocessing_manager
2258
(multiprocessing_manager
2261
new_client = (ClientDBusTransitional.__new__
2262
(ClientDBusTransitional))
2263
tcp_server.clients[client_name] = new_client
2264
new_client.bus = bus
2265
for name, value in client.iteritems():
2266
setattr(new_client, name, value)
2267
client_object_name = unicode(client_name).translate(
2268
{ord("."): ord("_"),
2269
ord("-"): ord("_")})
2270
new_client.dbus_object_path = (dbus.ObjectPath
2272
+ client_object_name))
2273
DBusObjectWithProperties.__init__(new_client,
2278
tcp_server.clients[client_name] = (Client.__new__
2280
for name, value in client.iteritems():
2281
setattr(tcp_server.clients[client_name],
2264
client["secret"] = (
2265
pgp.decrypt(client["encrypted_secret"],
2266
client_settings[client_name]
2285
tcp_server.clients[client_name].secret = (
2286
crypt.decrypt(tcp_server.clients[client_name]
2288
client_settings[client_name]
2269
2291
# If decryption fails, we use secret from new settings
2270
logger.debug("Failed to decrypt {0} old secret"
2271
.format(client_name))
2272
client["secret"] = (
2292
tcp_server.clients[client_name].secret = (
2273
2293
client_settings[client_name]["secret"])
2276
# Add/remove clients based on new changes made to config
2277
for client_name in (set(old_client_settings)
2278
- set(client_settings)):
2279
del clients_data[client_name]
2280
for client_name in (set(client_settings)
2281
- set(old_client_settings)):
2282
clients_data[client_name] = client_settings[client_name]
2284
# Create all client objects
2285
for client_name, client in clients_data.iteritems():
2286
tcp_server.clients[client_name] = client_class(
2287
name = client_name, settings = client)
2295
# Create/remove clients based on new changes made to config
2296
for clientname in set(old_client_settings) - set(client_settings):
2297
del tcp_server.clients[clientname]
2298
for clientname in set(client_settings) - set(old_client_settings):
2299
tcp_server.clients[clientname] = (client_class(name
2289
2305
if not tcp_server.clients:
2290
2306
logger.warning("No clients defined")
2398
2414
if attr not in exclude:
2399
2415
client_dict[attr] = getattr(client, attr)
2401
clients[client.name] = client_dict
2417
clients.append(client_dict)
2402
2418
del client_settings[client.name]["secret"]
2405
tempfd, tempname = tempfile.mkstemp(suffix=".pickle",
2408
(stored_state_path))
2409
with os.fdopen(tempfd, "wb") as stored_state:
2421
with os.fdopen(os.open(stored_state_path,
2422
os.O_CREAT|os.O_WRONLY|os.O_TRUNC,
2423
0600), "wb") as stored_state:
2410
2424
pickle.dump((clients, client_settings), stored_state)
2411
os.rename(tempname, stored_state_path)
2412
2425
except (IOError, OSError) as e:
2413
2426
logger.warning("Could not save persistent state: {0}"
2420
if e.errno not in set((errno.ENOENT, errno.EACCES,
2428
if e.errno not in (errno.ENOENT, errno.EACCES):
2424
2431
# Delete all clients, and settings from config
2425
2432
while tcp_server.clients: