def _delete_idle_service_vm_hosting_devices(self, context, num, template):
<EOL>num_deleted = <NUM_LIT:0><EOL>plugging_drv = self.get_hosting_device_plugging_driver(context,<EOL>template['<STR_LIT:id>'])<EOL>hosting_device_drv = self.get_hosting_device_driver(context,<EOL>template['<STR_LIT:id>'])<EOL>if plugging_drv is None or hosting_device_drv is None or num <= <NUM_LIT:0>:<EOL><INDENT>return num_deleted<EOL><DEDENT>query = context.session.query(hd_models.HostingDevice)<EOL>query = query.outerjoin(<EOL>hd_models.SlotAllocation,<EOL>hd_models.HostingDevice.id ==<EOL>hd_models.SlotAllocation.hosting_device_id)<EOL>query = query.filter(hd_models.HostingDevice.template_id ==<EOL>template['<STR_LIT:id>'],<EOL>hd_models.HostingDevice.admin_state_up ==<EOL>expr.true(),<EOL>hd_models.HostingDevice.tenant_bound ==<EOL>expr.null(),<EOL>hd_models.HostingDevice.auto_delete ==<EOL>expr.true())<EOL>query = query.group_by(hd_models.HostingDevice.id).having(<EOL>func.count(hd_models.SlotAllocation.logical_resource_id) == <NUM_LIT:0>)<EOL>query = query.order_by(<EOL>hd_models.HostingDevice.created_at.desc(),<EOL>func.count(hd_models.SlotAllocation.logical_resource_id))<EOL>hd_candidates = query.all()<EOL>num_possible_to_delete = min(len(hd_candidates), num)<EOL>for i in range(num_possible_to_delete):<EOL><INDENT>res = plugging_drv.get_hosting_device_resources(<EOL>context, hd_candidates[i]['<STR_LIT:id>'],<EOL>hd_candidates[i]['<STR_LIT>'], self.l3_tenant_id(),<EOL>self.mgmt_nw_id())<EOL>if self.svc_vm_mgr.delete_service_vm(context,<EOL>hd_candidates[i]['<STR_LIT:id>']):<EOL><INDENT>with context.session.begin(subtransactions=True):<EOL><INDENT>context.session.delete(hd_candidates[i])<EOL><DEDENT>plugging_drv.delete_hosting_device_resources(<EOL>context, self.l3_tenant_id(), **res)<EOL>num_deleted += <NUM_LIT:1><EOL><DEDENT><DEDENT>LOG.info('<STR_LIT>'<EOL>'<STR_LIT>', {'<STR_LIT>': num_deleted, '<STR_LIT>': template['<STR_LIT:id>']})<EOL>return num_deleted<EOL>
Deletes <num> or less unused <template>-based service VM instances.

        The number of deleted service vm instances is returned.