[linode] A more robust way to deal both with dict and object results.

This commit is contained in:
Fabio Manganiello 2024-09-26 01:50:52 +02:00
parent afdacc90d6
commit dc104a9c8e
Signed by untrusted user: blacklight
GPG key ID: D90FBA7F76362774

View file

@ -78,17 +78,18 @@ class LinodePlugin(RunnablePlugin, CloudInstanceEntityManager, EnumSwitchEntityM
if not key.startswith('_') if not key.startswith('_')
} }
@staticmethod
def _getattr(instance, key: str):
return getattr(instance, key, instance.get(key))
def main(self): def main(self):
instances = [] instances = []
while not self.should_stop(): while not self.should_stop():
status = { status = {self._getattr(instance, 'id'): instance for instance in instances}
getattr(instance, 'id', instance.get('id')): instance
for instance in instances
}
new_status = { new_status = {
instance['id']: instance self._getattr(instance, 'id'): instance
for instance in self.status(publish_entities=False).output for instance in self.status(publish_entities=False).output
} }
@ -97,8 +98,11 @@ class LinodePlugin(RunnablePlugin, CloudInstanceEntityManager, EnumSwitchEntityM
instance instance
for instance in new_status.values() for instance in new_status.values()
if not ( if not (
status.get(instance['id']) status.get(self._getattr(instance, 'id'))
and status[instance['id']].status == instance.status and self._getattr(
status[self._getattr(instance, 'id')], 'status'
)
== self._getattr(instance, 'status')
) )
] ]
if new_status if new_status
@ -109,12 +113,14 @@ class LinodePlugin(RunnablePlugin, CloudInstanceEntityManager, EnumSwitchEntityM
for instance in changed_instances: for instance in changed_instances:
get_bus().post( get_bus().post(
LinodeInstanceStatusChanged( LinodeInstanceStatusChanged(
instance_id=instance['id'], instance_id=self._getattr(instance, 'id'),
instance_name=instance['name'], instance_name=self._getattr(instance, 'label'),
status=instance['status'], status=self._getattr(instance, 'status'),
old_status=( old_status=(
status[instance['id']]['status'] self._getattr(
if status.get(instance['id']) status[self._getattr(instance, 'id')], 'status'
)
if status.get(self._getattr(instance, 'id'))
else None else None
), ),
) )
@ -178,8 +184,10 @@ class LinodePlugin(RunnablePlugin, CloudInstanceEntityManager, EnumSwitchEntityM
] ]
) )
mapped_instances = LinodeInstanceSchema(many=True).load( mapped_instances = list(
map(self._linode_instance_to_dict, instances) LinodeInstanceSchema(many=True).load( # type: ignore
map(self._linode_instance_to_dict, instances)
)
) )
if publish_entities: if publish_entities: