This patch fixes (at least) the following race conditions:
1. If a device is attached while iterating assigned devices, the
MonitorObserver thread can attempt to insert the newly attached
device to the assigned_devices set while the set is being iterated,
which results in the following exception:
RuntimeError: Set changed size during iteration
2. Some devices can be missed when applying a tuning - devices are enumerated
(i.e., Plugin._init_devices() gets called) before udev device monitoring is
started (hotplug.Plugin._hardware_events_init() gets called), so devices
that appear between these two actions are not tuned.
3. Device monitoring is stopped too late, which can result in some tunings
not being unapplied after stopping a profile. This can happen for devices
that get added during profile rollback after unit_manager.stop_tuning()
gets called, but before unit_manager.destroy_all() gets called.
4. It can happen that tuning is applied twice for a device if it is added
during profile activation, e.g. after unit_manager.create() is called in
Daemon._thread_code(), but before unit_manager.start_tuning() is called.
Apart from unnecessarily applying the tuning twice, it can result in
overwriting saved original settings for the device and hence our inability
to properly roll back our changes to the settings.
5. The observer thread can attempt to use load_monitor before it's created
in Plugin._instance_init(), which can result in AttributeError.
Hopefully it doesn't introduce new race conditions :).
The fix is to:
1. rearrange the sequence of certain actions,
2. separate Instance.devices to two separate sets: processed_devices
and assigned_devices.
processed_devices are never iterated when the MonitorObserver thread
is running (*), so the first problem described above cannot happen.
The set is used to store devices, which have already been tuned.
The assigned_devices set is now the set of devices that are going
to be tuned. The set can only be accessed by the main thread.
(*) Except when verifying tuning - this is fixed in a follow-up patch
I tried to separate the changes into more digestable patches, but I
couldn't figure out how.
Resolves: rhbz#1592743
Signed-off-by: Ondřej Lysoněk <olysonek@redhat.com>