461
462
def config_parser(config):
462
""" Construct a new dict of client settings of this form:
463
"""Construct a new dict of client settings of this form:
463
464
{ client_name: {setting_name: value, ...}, ...}
464
with exceptions for any special settings as defined above"""
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.
466
470
for client_name in config.sections():
467
471
section = dict(config.items(client_name))
468
472
client = settings[client_name] = {}
470
# Default copying each value from config to new dict
471
for setting, value in section.iteritems():
472
client[setting] = value
474
client["host"] = section["host"]
474
475
# Reformat values from string types to Python types
475
476
client["approved_by_default"] = config.getboolean(
476
477
client_name, "approved_by_default")
477
client["enabled"] = config.getboolean(client_name, "enabled")
478
client["enabled"] = config.getboolean(client_name,
479
481
client["fingerprint"] = (section["fingerprint"].upper()
480
482
.replace(" ", ""))
496
498
section["approval_delay"])
497
499
client["approval_duration"] = string_to_delta(
498
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
503
def __init__(self, config, name = None):
509
def __init__(self, settings, name = None):
504
510
"""Note: the 'checker' key in 'config' sets the
505
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
508
528
logger.debug("Creating client %r", self.name)
509
529
# Uppercase and remove spaces from fingerprint for later
510
530
# comparison purposes with return value from the fingerprint()
512
self.fingerprint = config["fingerprint"]
513
532
logger.debug(" Fingerprint: %s", self.fingerprint)
514
self.secret = config["secret"]
515
self.host = config["host"]
516
self.created = datetime.datetime.utcnow()
517
self.enabled = config["enabled"]
518
self.last_approval_request = None
520
self.last_enabled = datetime.datetime.utcnow()
522
self.last_enabled = None
523
self.last_checked_ok = None
524
self.last_checker_status = None
525
self.timeout = config["timeout"]
526
self.extended_timeout = config["extended_timeout"]
527
self.interval = config["interval"]
533
self.created = settings.get("created",
534
datetime.datetime.utcnow())
536
# attributes specific for this server instance
528
537
self.checker = None
529
538
self.checker_initiator_tag = None
530
539
self.disable_initiator_tag = None
532
self.expires = datetime.datetime.utcnow() + self.timeout
535
540
self.checker_callback_tag = None
536
self.checker_command = config["checker"]
537
541
self.current_checker_command = None
538
542
self.approved = None
539
self.approved_by_default = config["approved_by_default"]
540
543
self.approvals_pending = 0
541
self.approval_delay = config["approval_delay"]
542
self.approval_duration = config["approval_duration"]
543
544
self.changedstate = (multiprocessing_manager
544
545
.Condition(multiprocessing_manager
1365
1356
if value is None: # get
1366
1357
return dbus.UInt64(self.timeout_milliseconds())
1367
1358
self.timeout = datetime.timedelta(0, 0, 0, value)
1368
if getattr(self, "disable_initiator_tag", None) is None:
1370
1359
# Reschedule timeout
1371
gobject.source_remove(self.disable_initiator_tag)
1372
self.disable_initiator_tag = None
1374
time_to_die = timedelta_to_milliseconds((self
1379
if time_to_die <= 0:
1380
# The timeout has passed
1383
self.expires = (datetime.datetime.utcnow()
1384
+ datetime.timedelta(milliseconds =
1386
self.disable_initiator_tag = (gobject.timeout_add
1387
(time_to_die, self.disable))
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
1389
1379
# ExtendedTimeout - property
1390
1380
@dbus_service_property(_interface, signature="t",
2225
2211
if e.errno != errno.ENOENT:
2213
except EOFError as e:
2214
logger.warning("Could not load persistent state: "
2215
"EOFError: {0}".format(e))
2228
2217
with PGPEngine() as pgp:
2229
for client in clients_data:
2230
client_name = client["name"]
2218
for client_name, client in clients_data.iteritems():
2232
2219
# Decide which value to use after restoring saved state.
2233
2220
# We have three different values: Old config file,
2234
2221
# new config file, and saved state.
2249
2236
# Clients who has passed its expire date can still be
2250
2237
# enabled if its last checker was successful. Clients
2251
# whose checker failed before we stored its state is
2252
# assumed to have failed all checkers during downtime.
2238
# whose checker succeeded before we stored its state is
2239
# assumed to have successfully run all checkers during
2253
2241
if client["enabled"]:
2254
2242
if datetime.datetime.utcnow() >= client["expires"]:
2255
2243
if not client["last_checked_ok"]:
2256
2244
logger.warning(
2257
2245
"disabling client {0} - Client never "
2258
"performed a successfull checker"
2259
.format(client["name"]))
2246
"performed a successful checker"
2247
.format(client_name))
2260
2248
client["enabled"] = False
2261
2249
elif client["last_checker_status"] != 0:
2262
2250
logger.warning(
2263
2251
"disabling client {0} - Client "
2264
2252
"last checker failed with error code {1}"
2265
.format(client["name"],
2253
.format(client_name,
2266
2254
client["last_checker_status"]))
2267
2255
client["enabled"] = False
2269
2257
client["expires"] = (datetime.datetime
2271
2259
+ client["timeout"])
2273
client["changedstate"] = (multiprocessing_manager
2275
(multiprocessing_manager
2277
client["checker"] = None
2279
new_client = (ClientDBusTransitional.__new__
2280
(ClientDBusTransitional))
2281
tcp_server.clients[client_name] = new_client
2282
new_client.bus = bus
2283
for name, value in client.iteritems():
2284
setattr(new_client, name, value)
2285
client_object_name = unicode(client_name).translate(
2286
{ord("."): ord("_"),
2287
ord("-"): ord("_")})
2288
new_client.dbus_object_path = (dbus.ObjectPath
2290
+ client_object_name))
2291
DBusObjectWithProperties.__init__(new_client,
2296
tcp_server.clients[client_name] = (Client.__new__
2298
for name, value in client.iteritems():
2299
setattr(tcp_server.clients[client_name],
2260
logger.debug("Last checker succeeded,"
2261
" keeping {0} enabled"
2262
.format(client_name))
2303
tcp_server.clients[client_name].secret = (
2304
pgp.decrypt(tcp_server.clients[client_name]
2264
client["secret"] = (
2265
pgp.decrypt(client["encrypted_secret"],
2306
2266
client_settings[client_name]
2308
2268
except PGPError:
2309
2269
# If decryption fails, we use secret from new settings
2310
2270
logger.debug("Failed to decrypt {0} old secret"
2311
2271
.format(client_name))
2312
tcp_server.clients[client_name].secret = (
2272
client["secret"] = (
2313
2273
client_settings[client_name]["secret"])
2315
# Create/remove clients based on new changes made to config
2316
for clientname in set(old_client_settings) - set(client_settings):
2317
del tcp_server.clients[clientname]
2318
for clientname in set(client_settings) - set(old_client_settings):
2319
tcp_server.clients[clientname] = (client_class(name = clientname,
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)
2324
2289
if not tcp_server.clients:
2325
2290
logger.warning("No clients defined")
2433
2398
if attr not in exclude:
2434
2399
client_dict[attr] = getattr(client, attr)
2436
clients.append(client_dict)
2401
clients[client.name] = client_dict
2437
2402
del client_settings[client.name]["secret"]
2440
with os.fdopen(os.open(stored_state_path,
2441
os.O_CREAT|os.O_WRONLY|os.O_TRUNC,
2442
0600), "wb") as stored_state:
2405
tempfd, tempname = tempfile.mkstemp(suffix=".pickle",
2408
(stored_state_path))
2409
with os.fdopen(tempfd, "wb") as stored_state:
2443
2410
pickle.dump((clients, client_settings), stored_state)
2411
os.rename(tempname, stored_state_path)
2444
2412
except (IOError, OSError) as e:
2445
2413
logger.warning("Could not save persistent state: {0}"
2447
if e.errno not in (errno.ENOENT, errno.EACCES):
2420
if e.errno not in set((errno.ENOENT, errno.EACCES,
2450
2424
# Delete all clients, and settings from config
2451
2425
while tcp_server.clients: