412
413
interval: datetime.timedelta(); How often to start a new checker
413
414
last_approval_request: datetime.datetime(); (UTC) or None
414
415
last_checked_ok: datetime.datetime(); (UTC) or None
416
416
last_checker_status: integer between 0 and 255 reflecting exit
417
417
status of last checker. -1 reflects crashed
418
checker, -2 means no checker completed yet.
419
419
last_enabled: datetime.datetime(); (UTC) or None
420
420
name: string; from the config file, used in log messages and
421
421
D-Bus identifiers
422
422
secret: bytestring; sent verbatim (over TLS) to client
423
423
timeout: datetime.timedelta(); How long from last_checked_ok
424
424
until this client is disabled
425
extended_timeout: extra long timeout when password has been sent
425
extended_timeout: extra long timeout when secret has been sent
426
426
runtime_expansions: Allowed attributes for runtime expansion.
427
427
expires: datetime.datetime(); time (UTC) when a client will be
428
428
disabled, or None
432
432
"created", "enabled", "fingerprint",
433
433
"host", "interval", "last_checked_ok",
434
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",
436
446
def timeout_milliseconds(self):
437
447
"Return the 'timeout' attribute in milliseconds"
448
458
def approval_delay_milliseconds(self):
449
459
return timedelta_to_milliseconds(self.approval_delay)
451
def __init__(self, name = None, config=None):
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"] = -2
509
def __init__(self, settings, name = None):
452
510
"""Note: the 'checker' key in 'config' sets the
453
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
458
528
logger.debug("Creating client %r", self.name)
459
529
# Uppercase and remove spaces from fingerprint for later
460
530
# comparison purposes with return value from the fingerprint()
462
self.fingerprint = (config["fingerprint"].upper()
464
532
logger.debug(" Fingerprint: %s", self.fingerprint)
465
if "secret" in config:
466
self.secret = config["secret"].decode("base64")
467
elif "secfile" in config:
468
with open(os.path.expanduser(os.path.expandvars
469
(config["secfile"])),
471
self.secret = secfile.read()
473
raise TypeError("No secret or secfile for client %s"
475
self.host = config.get("host", "")
476
self.created = datetime.datetime.utcnow()
477
self.enabled = config.get("enabled", True)
478
self.last_approval_request = None
480
self.last_enabled = datetime.datetime.utcnow()
482
self.last_enabled = None
483
self.last_checked_ok = None
484
self.last_checker_status = None
485
self.timeout = string_to_delta(config["timeout"])
486
self.extended_timeout = string_to_delta(config
487
["extended_timeout"])
488
self.interval = string_to_delta(config["interval"])
533
self.created = settings.get("created",
534
datetime.datetime.utcnow())
536
# attributes specific for this server instance
489
537
self.checker = None
490
538
self.checker_initiator_tag = None
491
539
self.disable_initiator_tag = None
493
self.expires = datetime.datetime.utcnow() + self.timeout
496
540
self.checker_callback_tag = None
497
self.checker_command = config["checker"]
498
541
self.current_checker_command = None
499
542
self.approved = None
500
self.approved_by_default = config.get("approved_by_default",
502
543
self.approvals_pending = 0
503
self.approval_delay = string_to_delta(
504
config["approval_delay"])
505
self.approval_duration = string_to_delta(
506
config["approval_duration"])
507
544
self.changedstate = (multiprocessing_manager
508
545
.Condition(multiprocessing_manager
589
626
logger.warning("Checker for %(name)s crashed?",
592
def checked_ok(self, timeout=None):
593
"""Bump up the timeout for this client.
595
This should only be called when the client has been seen,
629
def checked_ok(self):
630
"""Assert that the client has been seen, alive and well."""
631
self.last_checked_ok = datetime.datetime.utcnow()
632
self.last_checker_status = 0
635
def bump_timeout(self, timeout=None):
636
"""Bump up the timeout for this client."""
598
637
if timeout is None:
599
638
timeout = self.timeout
600
self.last_checked_ok = datetime.datetime.utcnow()
601
639
if self.disable_initiator_tag is not None:
602
640
gobject.source_remove(self.disable_initiator_tag)
603
641
if getattr(self, "enabled", False):
1329
1365
if value is None: # get
1330
1366
return dbus.UInt64(self.timeout_milliseconds())
1331
1367
self.timeout = datetime.timedelta(0, 0, 0, value)
1332
if getattr(self, "disable_initiator_tag", None) is None:
1334
1368
# Reschedule timeout
1335
gobject.source_remove(self.disable_initiator_tag)
1336
self.disable_initiator_tag = None
1338
time_to_die = timedelta_to_milliseconds((self
1343
if time_to_die <= 0:
1344
# The timeout has passed
1347
self.expires = (datetime.datetime.utcnow()
1348
+ datetime.timedelta(milliseconds =
1350
self.disable_initiator_tag = (gobject.timeout_add
1351
(time_to_die, self.disable))
1370
now = datetime.datetime.utcnow()
1371
time_to_die = timedelta_to_milliseconds(
1372
(self.last_checked_ok + self.timeout) - now)
1373
if time_to_die <= 0:
1374
# The timeout has passed
1377
self.expires = (now +
1378
datetime.timedelta(milliseconds =
1380
if (getattr(self, "disable_initiator_tag", None)
1383
gobject.source_remove(self.disable_initiator_tag)
1384
self.disable_initiator_tag = (gobject.timeout_add
1353
1388
# ExtendedTimeout - property
1354
1389
@dbus_service_property(_interface, signature="t",
2182
2203
client_class = functools.partial(ClientDBusTransitional,
2185
special_settings = {
2186
# Some settings need to be accessd by special methods;
2187
# booleans need .getboolean(), etc. Here is a list of them:
2188
"approved_by_default":
2190
client_config.getboolean(section, "approved_by_default"),
2193
client_config.getboolean(section, "enabled"),
2195
# Construct a new dict of client settings of this form:
2196
# { client_name: {setting_name: value, ...}, ...}
2197
# with exceptions for any special settings as defined above
2198
client_settings = dict((clientname,
2201
if setting not in special_settings
2202
else special_settings[setting]
2204
for setting, value in
2205
client_config.items(clientname)))
2206
for clientname in client_config.sections())
2206
client_settings = Client.config_parser(client_config)
2208
2207
old_client_settings = {}
2211
2210
# Get client data and settings from last running state.
2212
2211
if server_settings["restore"]:
2245
2245
# Clients who has passed its expire date can still be
2246
# enabled if its last checker was sucessful. Clients
2247
# whose checker failed before we stored its state is
2248
# assumed to have failed all checkers during downtime.
2246
# enabled if its last checker was successful. Clients
2247
# whose checker succeeded before we stored its state is
2248
# assumed to have successfully run all checkers during
2249
2250
if client["enabled"]:
2250
if client["expires"] <= (datetime.datetime
2252
# Client has expired
2253
if client["last_checker_status"] != 0:
2251
if datetime.datetime.utcnow() >= client["expires"]:
2252
if not client["last_checked_ok"]:
2254
"disabling client {0} - Client never "
2255
"performed a successful checker"
2256
.format(client_name))
2257
client["enabled"] = False
2258
elif client["last_checker_status"] != 0:
2260
"disabling client {0} - Client "
2261
"last checker failed with error code {1}"
2262
.format(client_name,
2263
client["last_checker_status"]))
2254
2264
client["enabled"] = False
2256
2266
client["expires"] = (datetime.datetime
2258
2268
+ client["timeout"])
2260
client["changedstate"] = (multiprocessing_manager
2262
(multiprocessing_manager
2265
new_client = (ClientDBusTransitional.__new__
2266
(ClientDBusTransitional))
2267
tcp_server.clients[client_name] = new_client
2268
new_client.bus = bus
2269
for name, value in client.iteritems():
2270
setattr(new_client, name, value)
2271
client_object_name = unicode(client_name).translate(
2272
{ord("."): ord("_"),
2273
ord("-"): ord("_")})
2274
new_client.dbus_object_path = (dbus.ObjectPath
2276
+ client_object_name))
2277
DBusObjectWithProperties.__init__(new_client,
2282
tcp_server.clients[client_name] = (Client.__new__
2284
for name, value in client.iteritems():
2285
setattr(tcp_server.clients[client_name],
2269
logger.debug("Last checker succeeded,"
2270
" keeping {0} enabled"
2271
.format(client_name))
2289
tcp_server.clients[client_name].secret = (
2290
pgp.decrypt(tcp_server.clients[client_name]
2273
client["secret"] = (
2274
pgp.decrypt(client["encrypted_secret"],
2292
2275
client_settings[client_name]
2294
2277
except PGPError:
2295
2278
# If decryption fails, we use secret from new settings
2296
2279
logger.debug("Failed to decrypt {0} old secret"
2297
2280
.format(client_name))
2298
tcp_server.clients[client_name].secret = (
2281
client["secret"] = (
2299
2282
client_settings[client_name]["secret"])
2301
# Create/remove clients based on new changes made to config
2302
for clientname in set(old_client_settings) - set(client_settings):
2303
del tcp_server.clients[clientname]
2304
for clientname in set(client_settings) - set(old_client_settings):
2305
tcp_server.clients[clientname] = (client_class(name
2285
# Add/remove clients based on new changes made to config
2286
for client_name in (set(old_client_settings)
2287
- set(client_settings)):
2288
del clients_data[client_name]
2289
for client_name in (set(client_settings)
2290
- set(old_client_settings)):
2291
clients_data[client_name] = client_settings[client_name]
2293
# Create all client objects
2294
for client_name, client in clients_data.iteritems():
2295
tcp_server.clients[client_name] = client_class(
2296
name = client_name, settings = client)
2311
2298
if not tcp_server.clients:
2312
2299
logger.warning("No clients defined")
2420
2407
if attr not in exclude:
2421
2408
client_dict[attr] = getattr(client, attr)
2423
clients.append(client_dict)
2410
clients[client.name] = client_dict
2424
2411
del client_settings[client.name]["secret"]
2427
with os.fdopen(os.open(stored_state_path,
2428
os.O_CREAT|os.O_WRONLY|os.O_TRUNC,
2429
0600), "wb") as stored_state:
2414
tempfd, tempname = tempfile.mkstemp(suffix=".pickle",
2417
(stored_state_path))
2418
with os.fdopen(tempfd, "wb") as stored_state:
2430
2419
pickle.dump((clients, client_settings), stored_state)
2420
os.rename(tempname, stored_state_path)
2431
2421
except (IOError, OSError) as e:
2432
2422
logger.warning("Could not save persistent state: {0}"
2434
if e.errno not in (errno.ENOENT, errno.EACCES):
2429
if e.errno not in set((errno.ENOENT, errno.EACCES,
2437
2433
# Delete all clients, and settings from config
2438
2434
while tcp_server.clients: