When do hal properties get updated - dbus

I'm calling GetProperty on a org.freedesktop.Hal.Device from my handler during a PropertyNotified signal. I'm only calling GetProperty on properties that have been added or changed.
When I call GetProperty during property adds, I'm getting a org.freedesktop.Hal.NoSuchProperty exception. I'm also worried that during changes, I'm getting the old values.
When should I be calling GetProperty? What race conditions are involved?

How about DeviceExists method (like here):
if device.PropertyExists('info.product'):
return device.GetProperty('info.product')
return "unknown"
And PropertyModified signal, (ex from real world):
#
# _CBHalDeviceConnected
#
# INTERNAL
#
# Callback triggered when a device is connected through Hal.
#
def _CBHalDeviceConnected(self, obj_path):
...
self.device.connect_to_signal("PropertyModified",
self._CBHalDeviceAuthStateChanged)
...
#
# _CBHalDeviceAuthStateChanged
#
# INTERNAL
#
# Callback triggered when a Hal device property is changed,
# for checking authorization state changes
#
def _CBHalDeviceAuthStateChanged(self,num_changes,properties):
for property in properties:
property_name, added, removed = property
if property_name == "pda.pocketpc.password":
self.logger.info("_CBHalDeviceAuthStateChanged:
device authorization state changed: reauthorizing")
self._ProcessAuth()
HAL 0.5.10 Specification
D-Bus Specification
D-Bus Tutorial

Related

How to view multiple events with bot.wait_for?

I want to listen for many events with bot.wait_for and not a single event. First event blocks the second one when I arrange them back to back.
done, pending = await asyncio.wait([
bot.loop.create_task(bot.wait_for('message')),
bot.loop.create_task(bot.wait_for('reaction_add'))
], return_when=asyncio.FIRST_COMPLETED)
try:
stuff = done.pop().result()
except ...:
# If the first finished task died for any reason,
# the exception will be replayed here.
for future in done:
# If any exception happened in any other done tasks
# we don't care about the exception, but don't want the noise of
# non-retrieved exceptions
future.exception()
for future in pending:
future.cancel() # we don't need these anymore

getProperties method not found for NetworkManager

I am going through dbus-python tutorial.
https://dbus.freedesktop.org/doc/dbus-python/tutorial.html#interfaces-and-methods
The example provided does not work for me. I replaced the eth0 with 1 but still it throws an error.
import dbus
bus = dbus.SystemBus()
eth0 = bus.get_object('org.freedesktop.NetworkManager',
'/org/freedesktop/NetworkManager/Devices/eth0')
eth0_dev_iface = dbus.Interface(eth0,
dbus_interface='org.freedesktop.NetworkManager.Devices')
props = eth0_dev_iface.getProperties()
Error:
dbus.exceptions.DBusException: org.freedesktop.DBus.Error.AccessDenied: Rejected send
message, 2 matched rules; type="method_call", sender=":1.4371" (uid=78105 pid=8231
comm="python3 " label="unconfined") interface="org.freedesktop.NetworkManager.Devices"
member="getProperties" error name="(unset)" requested_reply="0" destination=":1.11"
(uid=0 pid=1122 comm="/usr/sbin/NetworkManager --no-daemon " label="unconfined")
Also there is this below statement
For instance, each NetworkManager object representing a network interface implements the interface org.freedesktop.NetworkManager.Devices, which has methods like getProperties.
I checked with d-feet, somehow the interface of network manager does not have getProperties method
'/org/freedesktop/NetworkManager/Devices/eth0' is not a D-Bus path that you'll see on NetworkManager's D-Bus API.
You said, you were checking with d-feet. There you'll see that on NetworkManager's D-Bus API, objects commonly have a number at the end. So D-Bus paths to device "objects" are named like /org/freedesktop/NetworkManager/Devices/1.
Try also busctl tree org.freedesktop.NetworkManager.
I checked with d-feet, somehow the interface of network manager does not have getProperties method
NetworkManager's D-Bus API doesn't literally have a getProperties method. It implements the standard D-Bus API with org.freedesktop.DBus.Properties interface as specified (https://dbus.freedesktop.org/doc/dbus-specification.html). Maybe the python bindings expose that as a getProperties() method...
Try:
$ busctl call org.freedesktop.NetworkManager /org/freedesktop/NetworkManager/Devices/1 org.freedesktop.DBus.Properties Get ss org.freedesktop.NetworkManager.Device Path`
and
$ busctl -j call org.freedesktop.NetworkManager /org/freedesktop/NetworkManager/Devices/1 org.freedesktop.DBus.Properties GetAll s org.freedesktop.NetworkManager.Device

DEBUG:snowflake.connector.connection:Rest object has been destroyed, cannot close session

Can some one please explain the technicality behind: "DEBUG:snowflake.connector.connection:Rest object has been destroyed, cannot close session"
The following Python was executed successfully:
try:
time_start = pd.Timestamp.now()
connection.execute(SQL)
df = pd.read_sql_query(SQL, engine)
time_end = pd.Timestamp.now()
timer = pd.Timedelta(time_end-time_start).microseconds/1000
print(timer)
except ProgrammingError as e:
if e.errno == 604:
print("timeout")
connection.cursor().execute("rollback")
else:
raise e
else:
connection.cursor().execute("commit")
finally:
connection.close()
engine.dispose()
logging.debug('-------- Finished --------' )
if to_csv:
col_names = df.columns.tolist()
if col_names_upper:
col_names = [x.upper() for x in col_names]
csv_file_name = 'data.csv'
csv_path = os.path.join(dir_path,csv_file_name)
if append:
mode='a'
else:
mode='w'
df.to_csv(csv_path,index=False, mode=mode, header=col_names)
return None
else:
return df.to_dict()
But when I checked the log file, I found the following at the end of the log:
DEBUG:snowflake.connector.network:SUCCESS
DEBUG:snowflake.connector.network:Active requests sessions: 0, idle: 4
DEBUG:snowflake.connector.network:ret[code] = None, after post request
DEBUG:snowflake.connector.connection:Session is closed
DEBUG:root:-------- Finished --------
DEBUG:snowflake.connector.connection:Rest object has been destroyed, cannot close session
DEBUG:snowflake.connector.connection:Rest object has been destroyed, cannot close session
I don't understand what it meant by:"DEBUG:snowflake.connector.connection:Rest object has been destroyed, cannot close session".
The message Rest object has been destroyed, cannot close session is printed by the Snowflake Python Connector's connection object typically when it is attempted for closure multiple times.
This is normal to observe when using a connection pool manager: The SQLAlchemy-based engine object will attempt to close all managed connection objects when engine.dispose() is called), and also due to Python's internal garbage collection that calls connection.__del__() on objects reaching zero reference counts.
The logger level for the message is intentionally DEBUG to not worry users about successive attempts at connection cleanup by the runtime and frameworks in use. It is safe to ignore this message as it appears after the connection was closed up successfully (indicated via the Session is closed message preceding it).

How to invoke a task twice in Thor

I need to invoke a task twice in Thor. In Rake, this could be accomplished by "re-enabling" it, but I can't find an equivalent in either of http://www.rubydoc.info/github/wycats/thor/master/Thor/Invocation or https://github.com/erikhuda/thor/wiki/Invocations
Some background, because of old code, sometimes I need to reset a database between tests (I know this is not ideal, but this is old code), so my scenario is like
desc "all-tests", "all the tests"
def all_tests
invoke :"clean-db"
invoke :"first-tests"
invoke :"clean-db"
invoke :"second-tests"
end
I had a very similar situation. What worked for me was calling the methods directly rather than using invoke. For example:
class Tests < Thor
desc('all', 'run all tests')
def all
setup()
invoke :some_test_suite
teardown()
setup()
invoke :some_other_test_suite
teardown()
# etc.
end
desc('setup', 'set up the test database')
def setup
# some setup tasks here
end
desc('teardown', 'tear down the test database')
def teardown
# some teardown tasks here
end
end

PeekMessage triggers WndProc callback

Yesterday I encountered the weirdest problem I have ever seen.
I wrote a module that should get a notification on USB plugs.
To do so, I created a dummy window and registered it to device change notifications using some interface's GUID.
The strange error occurs when PeekMessage is called.
at this point, some why, the window's WndProc callback is called, only when the peeked message is WM_DEVICECHANGE (we were registered to in the above code).
On any other message, the DispatchMessage triggers the callback, as expected.
code:
NotificationFilter.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
NotificationFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
NotificationFilter.dbcc_classguid = guid;
not = RegisterDeviceNotification(
hWnd, // events recipient
&NotificationFilter, // type of device
DEVICE_NOTIFY_WINDOW_HANDLE // type of recipient handle
);
In order to incorporate this module with the rest of my code which is asynchronous, using Reactor design pattern with Windows Events, and following the advice of stackoverflow community members, I incorporated MsgWaitForMultipleObjects in order to listen for events and windows messages as well.
code:
for (;;)
{
dwRetval = MsgWaitForMultipleObjects(cntEvents, arrEvents, FALSE, INFINITE, QS_ALLINPUT);
switch (dwRetval)
{
case WAIT_FAILED:
// failed. TODO: status
break;
// TODO: handle abandoned.
default:
if (dwRetval == cntEvents)
{
// Message has popped.
BOOL x = PeekMessage(&tMsg, hWnd, 0, 0, PM_REMOVE); <---- WM_DEVICECHANGE triggers the callback
if (x)
{
TranslateMessage(&tMsg);
DispatchMessage(&tMsg);
}
}
else if (dwRetval < cntEvents)
{
// event signaled
}
else
{
// TODO: status. unexpected.
return FALSE; // unexpected failure
}
break;
}
}
I disassembled the code, and compared the registers before any call to NtUserPeekMessage
Registers on successful call:
RAX = 00000059A604EFB0 RBX = 0000000000000000 RCX = 00000059A604EF18
RDX = 0000000000070C62 RSI = 00000059A604EF18 RDI = 0000000000070C62
R8  = 0000000000000000 R9  = 0000000000000000 R10 = 00007FF71A65D800
R11 = 0000000000000246 R12 = 0000000000000000 R13 = 0000000000000000
R14 = 0000000000000000 R15 = 0000000000000000 RIP = 00007FF954562AA1
RSP = 00000059A604EE70 RBP = 0000000000000000 EFL = 00000200
Registers on unknown callback trigger call:
RAX = 00000059A604EFB0 RBX = 0000000000000000 RCX = 00000059A604EF18
RDX = 0000000000070C62 RSI = 00000059A604EF18 RDI = 0000000000070C62
R8  = 0000000000000000 R9  = 0000000000000000 R10 = 00007FF71A65D800
R11 = 0000000000000246 R12 = 0000000000000000 R13 = 0000000000000000
R14 = 0000000000000000 R15 = 0000000000000000 RIP = 00007FF954562AA1
RSP = 00000059A604EE70 RBP = 0000000000000000 EFL = 00000200
The registers are exactly the same! (No parameters are passed on the stack, 64bit..)
In both cases (strange error and expected flow) I stepped into at NtUserPeekMessage, it turns out that the WndProc callback is triggered only from the internal syscall!
00007FF954562A80 mov r10,rcx
00007FF954562A83 mov eax,1003h
00007FF954562A88 syscall
I couldn't find any documentation on MSDN or explanation on the internet to the phenomenon.
I would really like some help,
Thanks in advance.
That is as expected, and is documented. PeekMessage is one of the functions that dispatches sent messages. From the documentation:
Dispatches incoming sent messages, checks the thread message queue for a posted message, and retrieves the message (if any exist).
And then later in the same document:
During this call, the system delivers pending, nonqueued messages, that is, messages sent to windows owned by the calling thread using the SendMessage, SendMessageCallback, SendMessageTimeout, or SendNotifyMessage function.
The documentation for SendMessage says this (with my emphasis):
If the specified window was created by the calling thread, the window procedure is called immediately as a subroutine. If the specified window was created by a different thread, the system switches to that thread and calls the appropriate window procedure. Messages sent between threads are processed only when the receiving thread executes message retrieval code.
By message retrieval code the documentation means functions like GetMessage and PeekMessage. There are a few others, I don't have a comprehensive list at hand.

Resources