'Align power states between the database and the hypervisor.
To sync power state data we make a DB call to get the number of
virtual machines known by the hypervisor and if the number matches the
number of virtual machines known by the database, we proceed in a lazy
loop, one database record at a time, checking if the hypervisor has the
same power state as is in the database.'

@periodic_task.periodic_task(spacing=CONF.sync_power_state_interval, run_immediately=True)
def _sync_power_states(self, context):

    db_instances = objects.InstanceList.get_by_host(context, self.host, expected_attrs=[], use_slave=True)
    num_vm_instances = self.driver.get_num_instances()
    num_db_instances = len(db_instances)
    if (num_vm_instances != num_db_instances):
        LOG.warning('While    synchronizing    instance    power    states,    found    %(num_db_instances)s    instances    in    the    database    and    %(num_vm_instances)s    instances    on    the    hypervisor.', {'num_db_instances': num_db_instances, 'num_vm_instances': num_vm_instances})
    def _sync(db_instance):
        @utils.synchronized(db_instance.uuid)
        def query_driver_power_state_and_sync():
            self._query_driver_power_state_and_sync(context, db_instance)
        try:
            query_driver_power_state_and_sync()
        except Exception:
            LOG.exception('Periodic    sync_power_state    task    had    an    error    while    processing    an    instance.', instance=db_instance)
        self._syncs_in_progress.pop(db_instance.uuid)
    for db_instance in db_instances:
        uuid = db_instance.uuid
        if (uuid in self._syncs_in_progress):
            LOG.debug('Sync    already    in    progress    for    %s', uuid)
        else:
            LOG.debug('Triggering    sync    for    uuid    %s', uuid)
            self._syncs_in_progress[uuid] = True
            self._sync_power_pool.spawn_n(_sync, db_instance)
