diff --git a/changes/35601-optimize-cleanup-apple-profiles-query b/changes/35601-optimize-cleanup-apple-profiles-query new file mode 100644 index 0000000000..1cab47c7ae --- /dev/null +++ b/changes/35601-optimize-cleanup-apple-profiles-query @@ -0,0 +1 @@ +* Optimized the cleanup Apple host profiles query to reduce probability of DB locking. \ No newline at end of file diff --git a/server/datastore/mysql/apple_mdm.go b/server/datastore/mysql/apple_mdm.go index 95f418cecd..6fcdbcb762 100644 --- a/server/datastore/mysql/apple_mdm.go +++ b/server/datastore/mysql/apple_mdm.go @@ -6754,13 +6754,23 @@ func (ds *Datastore) CleanupHostMDMAppleProfiles(ctx context.Context) error { // This could also occur due to errors (i.e., large server/DB load) or server being stopped while processing the profiles. // After the entry is deleted, the mdm_apple_profile_manager job will try to requeue the profile. stmt := fmt.Sprintf(` - DELETE hmap FROM host_mdm_apple_profiles AS hmap - -- ANTIJOIN: Delete rows that don't have a corresponding entry in nano_enrollment_queue - -- Note that a given host may have multiple nano_enrollments(device and user) and thus we - -- need to account for the use of either of them in the join - LEFT JOIN (nano_enrollment_queue neq INNER JOIN nano_enrollments ne ON neq.id = ne.id AND ne.enabled = 1) - ON ne.device_id = hmap.host_uuid AND hmap.command_uuid = neq.command_uuid AND neq.active = 1 - WHERE neq.id IS NULL AND (hmap.status IS NULL OR hmap.status = '%s') AND hmap.updated_at < NOW() - INTERVAL 1 HOUR`, + DELETE hmap FROM host_mdm_apple_profiles AS hmap +WHERE ( + hmap.status IS NULL + OR hmap.status = '%s' + ) + AND hmap.updated_at < NOW() - INTERVAL 1 HOUR + AND NOT EXISTS ( + SELECT 1 + FROM + nano_enrollments ne + STRAIGHT_JOIN nano_enrollment_queue neq ON neq.id = ne.id + AND neq.command_uuid = hmap.command_uuid + AND neq.active = 1 + WHERE + ne.device_id = hmap.host_uuid + AND ne.enabled = 1 + );`, fleet.MDMDeliveryPending) if _, err := ds.writer(ctx).ExecContext(ctx, stmt); err != nil { return ctxerr.Wrap(ctx, err, "delete from host_mdm_apple_profiles")