Browse Source

Serialize concurrent active alarm creation per originator and type in BaseAlarmService

Replaces the pg_advisory_xact_lock in create_or_update_active_alarm with a Guava
Striped lock around the DAO call, and removes the 4.2.2.7 upgrade script and
migration that only shipped the SQL function change.
pull/15641/head
Oleksandra Matviienko 1 month ago
parent
commit
4a9f4f90fc
  1. 86
      application/src/main/data/upgrade/lts/4.2.2.7/schema_update.sql
  2. 17
      application/src/main/java/org/thingsboard/server/service/install/lts/V4_2_2_7Migration.java
  3. 14
      dao/src/main/java/org/thingsboard/server/dao/alarm/BaseAlarmService.java
  4. 7
      dao/src/main/resources/sql/schema-functions.sql

86
application/src/main/data/upgrade/lts/4.2.2.7/schema_update.sql

@ -1,86 +0,0 @@
--
-- SPDX-FileCopyrightText: Copyright The Thingsboard Authors
-- SPDX-License-Identifier: Apache-2.0
--
-- CREATE_OR_UPDATE_ACTIVE_ALARM CONCURRENT DUPLICATE FIX START
CREATE OR REPLACE FUNCTION create_or_update_active_alarm(
t_id uuid, c_id uuid, a_id uuid, a_created_ts bigint,
a_o_id uuid, a_o_type integer, a_type varchar,
a_severity varchar, a_start_ts bigint, a_end_ts bigint,
a_details varchar,
a_propagate boolean, a_propagate_to_owner boolean,
a_propagate_to_tenant boolean, a_propagation_types varchar,
a_creation_enabled boolean)
RETURNS varchar
LANGUAGE plpgsql
AS
$$
DECLARE
null_id constant uuid = '13814000-1dd2-11b2-8080-808080808080'::uuid;
existing alarm;
result alarm_info;
row_count integer;
BEGIN
-- Serialize concurrent callers for the same (originator, type) so that the SELECT/INSERT
-- pair below cannot interleave and produce duplicate active alarms.
-- Correctness relies on READ COMMITTED (ThingsBoard's default isolation level): after the
-- lock is granted, the SELECT below takes a fresh per-statement snapshot and sees the row a
-- prior caller just committed. Under REPEATABLE READ / SERIALIZABLE the transaction's older
-- snapshot would miss that row and INSERT a duplicate, so do not call this under those levels.
PERFORM pg_advisory_xact_lock(hashtext(a_o_id::text), hashtext(a_type));
SELECT * INTO existing FROM alarm a WHERE a.originator_id = a_o_id AND a.type = a_type AND a.cleared = false ORDER BY a.start_ts DESC FOR UPDATE;
IF existing.id IS NULL THEN
IF a_creation_enabled = FALSE THEN
RETURN json_build_object('success', false)::text;
END IF;
IF c_id = null_id THEN
c_id = NULL;
end if;
INSERT INTO alarm
(tenant_id, customer_id, id, created_time,
originator_id, originator_type, type,
severity, start_ts, end_ts,
additional_info,
propagate, propagate_to_owner, propagate_to_tenant, propagate_relation_types,
acknowledged, ack_ts,
cleared, clear_ts,
assignee_id, assign_ts)
VALUES
(t_id, c_id, a_id, a_created_ts,
a_o_id, a_o_type, a_type,
a_severity, a_start_ts, a_end_ts,
a_details,
a_propagate, a_propagate_to_owner, a_propagate_to_tenant, a_propagation_types,
false, 0, false, 0, NULL, 0);
INSERT INTO alarm_types (tenant_id, type) VALUES (t_id, a_type) ON CONFLICT (tenant_id, type) DO NOTHING;
SELECT * INTO result FROM alarm_info a WHERE a.id = a_id AND a.tenant_id = t_id;
RETURN json_build_object('success', true, 'created', true, 'modified', true, 'alarm', row_to_json(result))::text;
ELSE
UPDATE alarm a
SET severity = a_severity,
start_ts = a_start_ts,
end_ts = a_end_ts,
additional_info = a_details,
propagate = a_propagate,
propagate_to_owner = a_propagate_to_owner,
propagate_to_tenant = a_propagate_to_tenant,
propagate_relation_types = a_propagation_types
WHERE a.id = existing.id
AND a.tenant_id = t_id
AND (severity != a_severity OR start_ts != a_start_ts OR end_ts != a_end_ts OR additional_info != a_details
OR propagate != a_propagate OR propagate_to_owner != a_propagate_to_owner OR
propagate_to_tenant != a_propagate_to_tenant OR propagate_relation_types != a_propagation_types);
GET DIAGNOSTICS row_count = ROW_COUNT;
SELECT * INTO result FROM alarm_info a WHERE a.id = existing.id AND a.tenant_id = t_id;
IF row_count > 0 THEN
RETURN json_build_object('success', true, 'modified', true, 'alarm', row_to_json(result), 'old', row_to_json(existing))::text;
ELSE
RETURN json_build_object('success', true, 'modified', false, 'alarm', row_to_json(result))::text;
END IF;
END IF;
END
$$;
-- CREATE_OR_UPDATE_ACTIVE_ALARM CONCURRENT DUPLICATE FIX END

17
application/src/main/java/org/thingsboard/server/service/install/lts/V4_2_2_7Migration.java

@ -1,17 +0,0 @@
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.service.install.lts;
import org.springframework.stereotype.Component;
import org.thingsboard.server.queue.util.TbCoreComponent;
@Component
@TbCoreComponent
public class V4_2_2_7Migration implements LtsMigration {
@Override
public String getVersion() {
return "4.2.2.7";
}
}

14
dao/src/main/java/org/thingsboard/server/dao/alarm/BaseAlarmService.java

@ -5,6 +5,7 @@ package org.thingsboard.server.dao.alarm;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.util.concurrent.FluentFuture;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.Striped;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@ -64,6 +65,7 @@ import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.locks.Lock;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@ -79,11 +81,14 @@ public class BaseAlarmService extends AbstractCachedEntityService<TenantId, Page
public static final String INCORRECT_TENANT_ID = "Incorrect tenantId ";
private static final PageLink DEFAULT_ALARM_TYPES_PAGE_LINK = new PageLink(25, 0, null, new SortOrder("type"));
private static final int ACTIVE_ALARM_LOCK_STRIPES = 1024;
private final TenantService tenantService;
private final AlarmDao alarmDao;
private final EntityService entityService;
private final Striped<Lock> activeAlarmLocks = Striped.lock(ACTIVE_ALARM_LOCK_STRIPES);
@Override
@TransactionalEventListener
public void handleEvictEvent(AlarmTypesCacheEvictEvent event) {
@ -117,7 +122,14 @@ public class BaseAlarmService extends AbstractCachedEntityService<TenantId, Page
throw new DataValidationException("Can't assign alarm to customer. Originator belongs to different customer!");
}
request.setCustomerId(customerId);
AlarmApiCallResult result = alarmDao.createOrUpdateActiveAlarm(request, alarmCreationEnabled);
AlarmApiCallResult result;
Lock lock = activeAlarmLocks.get(List.of(request.getOriginator().getId(), request.getType()));
lock.lock();
try {
result = alarmDao.createOrUpdateActiveAlarm(request, alarmCreationEnabled);
} finally {
lock.unlock();
}
if (!result.isSuccessful() && !alarmCreationEnabled) {
throw new ApiUsageLimitsExceededException("Alarms creation is disabled");
}

7
dao/src/main/resources/sql/schema-functions.sql

@ -21,13 +21,6 @@ DECLARE
result alarm_info;
row_count integer;
BEGIN
-- Serialize concurrent callers for the same (originator, type) so that the SELECT/INSERT
-- pair below cannot interleave and produce duplicate active alarms.
-- Correctness relies on READ COMMITTED (ThingsBoard's default isolation level): after the
-- lock is granted, the SELECT below takes a fresh per-statement snapshot and sees the row a
-- prior caller just committed. Under REPEATABLE READ / SERIALIZABLE the transaction's older
-- snapshot would miss that row and INSERT a duplicate, so do not call this under those levels.
PERFORM pg_advisory_xact_lock(hashtext(a_o_id::text), hashtext(a_type));
SELECT * INTO existing FROM alarm a WHERE a.originator_id = a_o_id AND a.type = a_type AND a.cleared = false ORDER BY a.start_ts DESC FOR UPDATE;
IF existing.id IS NULL THEN
IF a_creation_enabled = FALSE THEN

Loading…
Cancel
Save