From 220002f5f142e942fdc64a5fe94e77ed1712b71b Mon Sep 17 00:00:00 2001 From: Oleksandra Matviienko Date: Mon, 7 Sep 2026 11:16:35 +0200 Subject: [PATCH 01/21] Evaluate stored telemetry for duration alarm condition when schedule window opens --- .../cf/ctx/state/alarm/AlarmRuleState.java | 7 +++- .../thingsboard/server/cf/AlarmRulesTest.java | 42 +++++++++++++++++++ 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/cf/ctx/state/alarm/AlarmRuleState.java b/application/src/main/java/org/thingsboard/server/service/cf/ctx/state/alarm/AlarmRuleState.java index ada94dacda..833a51b770 100644 --- a/application/src/main/java/org/thingsboard/server/service/cf/ctx/state/alarm/AlarmRuleState.java +++ b/application/src/main/java/org/thingsboard/server/service/cf/ctx/state/alarm/AlarmRuleState.java @@ -81,10 +81,10 @@ public class AlarmRuleState { public AlarmEvalResult reeval(long ts, CalculatedFieldCtx ctx) { // on scheduled duration check or periodic re-eval for rules with schedule boolean active = isActive(ts); + boolean activeChanged = this.active == null || active != this.active; + this.active = active; switch (condition.getType()) { case SIMPLE, REPEATING -> { - boolean activeChanged = this.active == null || active != this.active; - this.active = active; if (!active) { return AlarmEvalResult.EMPTY; } @@ -103,6 +103,9 @@ public class AlarmRuleState { if (!active) { return AlarmEvalResult.FALSE; } + if (firstEventTs <= 0 && condition.hasSchedule() && activeChanged) { + return doEval(false, ctx); + } long requiredDuration = getRequiredDurationInMs(); if (requiredDuration > 0 && firstEventTs > 0 && ts > firstEventTs) { duration = ts - firstEventTs; diff --git a/application/src/test/java/org/thingsboard/server/cf/AlarmRulesTest.java b/application/src/test/java/org/thingsboard/server/cf/AlarmRulesTest.java index 9a001e0575..9e90e4131f 100644 --- a/application/src/test/java/org/thingsboard/server/cf/AlarmRulesTest.java +++ b/application/src/test/java/org/thingsboard/server/cf/AlarmRulesTest.java @@ -875,6 +875,48 @@ public class AlarmRulesTest extends AbstractControllerTest { }); } + @Test + public void testCreateAlarm_durationCondition_scheduleStarted() throws Exception { + Argument motionDetectedArgument = new Argument(); + motionDetectedArgument.setRefEntityKey(new ReferencedEntityKey("motionDetected", ArgumentType.TS_LATEST, null)); + motionDetectedArgument.setDefaultValue("false"); + Map arguments = Map.of( + "motionDetected", motionDetectedArgument + ); + + SpecificTimeSchedule schedule = new SpecificTimeSchedule(); + schedule.setTimezone(ZoneId.systemDefault().getId()); + schedule.setDaysOfWeek(Set.of(1, 2, 3, 4, 5, 6, 7)); + long startsOn = Duration.between(LocalDate.now().atStartOfDay(), LocalDateTime.now()) + .plus(15, ChronoUnit.SECONDS).toMillis(); + schedule.setStartsOn(startsOn); + Map createRules = Map.of( + AlarmSeverity.CRITICAL, new Condition("return motionDetected == true;", null, null, + new AlarmConditionValue<>(1000L, null), + new AlarmConditionValue<>(schedule, null)) + ); + + AlarmRuleDefinition alarmRule = createAlarmRule(deviceId, "Motion detected alarm", + arguments, createRules, null); + + postTelemetry(deviceId, "{\"motionDetected\":true}"); + + Thread.sleep(10000); + assertThat(getLatestAlarmResult(alarmRule.getId())).isNull(); + + // no new telemetry after the schedule window opens, so the stored value must be used + await().atMost(TIMEOUT, TimeUnit.SECONDS).untilAsserted(() -> { + CalculatedFieldDebugEvent debugEvent = getDebugEvents(alarmRule.getId(), 5).stream() + .filter(event -> event.getResult() != null) + .findFirst().orElse(null); + assertThat(debugEvent).isNotNull(); + TbAlarmResult alarmResult = JacksonUtil.fromString(debugEvent.getResult(), TbAlarmResult.class); + assertThat(alarmResult.isCreated()).isTrue(); + assertThat(alarmResult.getAlarm().getSeverity()).isEqualTo(AlarmSeverity.CRITICAL); + assertThat(alarmResult.getAlarm().getStatus()).isEqualTo(AlarmStatus.ACTIVE_UNACK); + }); + } + @Test public void testManualClearAlarm() throws Exception { Argument temperatureArgument = new Argument(); From d8699f430d4369e56da5d9904ac5f64c4426dfff Mon Sep 17 00:00:00 2001 From: Vladyslav_Prykhodko Date: Wed, 11 Nov 2026 15:40:31 +0200 Subject: [PATCH 02/21] Add unit tests for duration alarm rule re-evaluation when schedule window opens --- .../ctx/state/alarm/AlarmRuleStateTest.java | 143 ++++++++++++++++++ 1 file changed, 143 insertions(+) create mode 100644 application/src/test/java/org/thingsboard/server/service/cf/ctx/state/alarm/AlarmRuleStateTest.java diff --git a/application/src/test/java/org/thingsboard/server/service/cf/ctx/state/alarm/AlarmRuleStateTest.java b/application/src/test/java/org/thingsboard/server/service/cf/ctx/state/alarm/AlarmRuleStateTest.java new file mode 100644 index 0000000000..a55c2ce738 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/cf/ctx/state/alarm/AlarmRuleStateTest.java @@ -0,0 +1,143 @@ +/** + * Copyright © 2016-2026 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.service.cf.ctx.state.alarm; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.thingsboard.server.common.data.alarm.AlarmSeverity; +import org.thingsboard.server.common.data.alarm.rule.AlarmRule; +import org.thingsboard.server.common.data.alarm.rule.condition.AlarmConditionValue; +import org.thingsboard.server.common.data.alarm.rule.condition.DurationAlarmCondition; +import org.thingsboard.server.common.data.alarm.rule.condition.expression.AlarmConditionFilter; +import org.thingsboard.server.common.data.alarm.rule.condition.expression.SimpleAlarmConditionExpression; +import org.thingsboard.server.common.data.alarm.rule.condition.expression.predicate.NumericFilterPredicate; +import org.thingsboard.server.common.data.alarm.rule.condition.expression.predicate.NumericFilterPredicate.NumericOperation; +import org.thingsboard.server.common.data.alarm.rule.condition.schedule.SpecificTimeSchedule; +import org.thingsboard.server.common.data.cf.CalculatedField; +import org.thingsboard.server.common.data.cf.configuration.AlarmCalculatedFieldConfiguration; +import org.thingsboard.server.common.data.id.DeviceId; +import org.thingsboard.server.common.data.kv.DoubleDataEntry; +import org.thingsboard.server.common.data.query.EntityKeyValueType; +import org.thingsboard.server.service.cf.ctx.state.CalculatedFieldCtx; +import org.thingsboard.server.service.cf.ctx.state.SingleValueArgumentEntry; + +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class AlarmRuleStateTest { + + private static final DeviceId DEVICE_ID = new DeviceId(UUID.fromString("5512071d-5abc-411d-a907-4cdb6539c2eb")); + + // Schedule window: every day from 10:00 to 24:00 UTC + private static final long DAY_START_TS = Instant.parse("2024-01-15T00:00:00Z").toEpochMilli(); + private static final long WINDOW_STARTS_ON_MS = TimeUnit.HOURS.toMillis(10); + private static final long TELEMETRY_TS = DAY_START_TS + TimeUnit.HOURS.toMillis(8); + private static final long WINDOW_OPENED_TS = DAY_START_TS + WINDOW_STARTS_ON_MS + TimeUnit.SECONDS.toMillis(1); + + private static final long SHORT_DURATION_MS = TimeUnit.MINUTES.toMillis(1); + // AlarmRuleState.evalDuration() measures the duration against the wall clock, so to have a duration + // that has not elapsed yet for a telemetry ts fixed in the past, it has to be far longer than the time since then. + private static final long LONG_DURATION_MS = TimeUnit.DAYS.toMillis(365 * 1000); + + private final CalculatedFieldCtx ctx = mock(CalculatedFieldCtx.class); + + private AlarmCalculatedFieldState state; + + @BeforeEach + void setUp() { + AlarmCalculatedFieldConfiguration configuration = new AlarmCalculatedFieldConfiguration(); + configuration.setCreateRules(Map.of()); + CalculatedField calculatedField = new CalculatedField(); + calculatedField.setName("Test alarm"); + calculatedField.setConfiguration(configuration); + when(ctx.getCalculatedField()).thenReturn(calculatedField); + when(ctx.getArgNames()).thenReturn(List.of("temperature")); + + state = new AlarmCalculatedFieldState(DEVICE_ID); + state.setCtx(ctx, null); + // stored telemetry that satisfies the condition, received while the schedule window was closed + state.update(Map.of("temperature", new SingleValueArgumentEntry(TELEMETRY_TS, new DoubleDataEntry("temperature", 30.0), 1L)), ctx); + } + + @Test + void testReevalDurationWithoutSchedule_doesNotStartTimerFromStoredValue() { + // re-evaluated without a new event because another rule of the same calculated field has a schedule + AlarmRuleState ruleState = createRuleState(SHORT_DURATION_MS, false); + + AlarmEvalResult result = ruleState.reeval(WINDOW_OPENED_TS, ctx); + + assertThat(result.getStatus()).isNull(); + assertThat(ruleState.getFirstEventTs()).isZero(); + } + + @Test + void testReevalDurationWithSchedule_whenWindowOpensAndDurationElapsed_thenTrue() { + AlarmRuleState ruleState = createRuleState(SHORT_DURATION_MS, true); + + AlarmEvalResult result = ruleState.reeval(WINDOW_OPENED_TS, ctx); + + assertThat(result.getStatus()).isEqualTo(AlarmEvalResult.Status.TRUE); + assertThat(ruleState.getFirstEventTs()).isEqualTo(TELEMETRY_TS); + } + + @Test + void testReevalDurationWithSchedule_whenWindowOpensAndDurationNotElapsed_thenTimerStarted() { + // leftDuration of the result is what AlarmCalculatedFieldState uses to schedule the next duration check + AlarmRuleState ruleState = createRuleState(LONG_DURATION_MS, true); + + AlarmEvalResult result = ruleState.reeval(WINDOW_OPENED_TS, ctx); + + assertThat(result.getStatus()).isEqualTo(AlarmEvalResult.Status.NOT_YET_TRUE); + assertThat(result.getLeftDuration()).isPositive(); + assertThat(ruleState.getFirstEventTs()).isEqualTo(TELEMETRY_TS); + } + + private AlarmRuleState createRuleState(long durationMs, boolean withSchedule) { + DurationAlarmCondition condition = new DurationAlarmCondition(); + condition.setExpression(createTemperatureGreaterThanExpression(25.0)); + condition.setUnit(TimeUnit.MILLISECONDS); + condition.setValue(new AlarmConditionValue<>(durationMs, null)); + if (withSchedule) { + SpecificTimeSchedule schedule = new SpecificTimeSchedule(); + schedule.setTimezone("UTC"); + schedule.setDaysOfWeek(Set.of(1, 2, 3, 4, 5, 6, 7)); + schedule.setStartsOn(WINDOW_STARTS_ON_MS); + condition.setSchedule(new AlarmConditionValue<>(schedule, null)); + } + AlarmRule rule = new AlarmRule(); + rule.setCondition(condition); + return new AlarmRuleState(AlarmSeverity.CRITICAL, rule, state); + } + + private SimpleAlarmConditionExpression createTemperatureGreaterThanExpression(double threshold) { + AlarmConditionFilter filter = new AlarmConditionFilter(); + filter.setArgument("temperature"); + filter.setValueType(EntityKeyValueType.NUMERIC); + filter.setPredicates(List.of(new NumericFilterPredicate(NumericOperation.GREATER, new AlarmConditionValue<>(threshold, null)))); + SimpleAlarmConditionExpression expression = new SimpleAlarmConditionExpression(); + expression.setFilters(List.of(filter)); + return expression; + } + +} From 283a0804d1b6f2ff3aac67ac3fa0cf28c7f68fc9 Mon Sep 17 00:00:00 2001 From: Vladyslav_Prykhodko Date: Wed, 11 Nov 2026 15:41:56 +0200 Subject: [PATCH 03/21] Use SPDX license header in AlarmRuleStateTest --- .../cf/ctx/state/alarm/AlarmRuleStateTest.java | 17 ++--------------- 1 file changed, 2 insertions(+), 15 deletions(-) diff --git a/application/src/test/java/org/thingsboard/server/service/cf/ctx/state/alarm/AlarmRuleStateTest.java b/application/src/test/java/org/thingsboard/server/service/cf/ctx/state/alarm/AlarmRuleStateTest.java index a55c2ce738..2d04459fe6 100644 --- a/application/src/test/java/org/thingsboard/server/service/cf/ctx/state/alarm/AlarmRuleStateTest.java +++ b/application/src/test/java/org/thingsboard/server/service/cf/ctx/state/alarm/AlarmRuleStateTest.java @@ -1,18 +1,5 @@ -/** - * Copyright © 2016-2026 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors +// SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.service.cf.ctx.state.alarm; import org.junit.jupiter.api.BeforeEach; From 0cd8a802103557e5107d26bfe5973b56924b22f7 Mon Sep 17 00:00:00 2001 From: Vladyslav Prykhodko Date: Wed, 11 Nov 2026 23:04:14 +0200 Subject: [PATCH 04/21] Sped up the license header check: changed files in pull requests, parallel subprocesses, CE normalization cache - Pull requests check the files they change (--since), with a full check when the CE bases, the Mycila configuration or the check itself changed. - One history walk for CE deletions instead of one per CE base. - Distinct three-way merges run once and in parallel; Mycila invocations no longer share pom.xml/report.json and run in parallel. - The copy search skips CE files that Git cannot match by size. - Header-free CE contents are cached in target/license-headers-cache; pushes save the cache, pull requests only restore it. --- .github/workflows/check-license-headers.yml | 29 +- check-license-headers.sh | 6 +- .../src/main/python/license-headers/README.md | 33 +- .../license-headers/check_license_headers.py | 442 +++++++++++++++--- .../test_check_license_headers.py | 440 ++++++++++++++++- 5 files changed, 872 insertions(+), 78 deletions(-) diff --git a/.github/workflows/check-license-headers.yml b/.github/workflows/check-license-headers.yml index 753a9c565d..d8cebb1815 100644 --- a/.github/workflows/check-license-headers.yml +++ b/.github/workflows/check-license-headers.yml @@ -46,10 +46,37 @@ jobs: java-version: 21 cache: maven + # Header-free CE contents from earlier runs. A pull request reads the cache of its base branch, then of master; + # only pushes and manual runs write one, so a pull request never feeds the cache that other runs trust. + - name: Restore normalized CE contents + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: target/license-headers-cache + key: license-headers-ce-v1-${{ github.ref_name }}-${{ github.run_id }} + restore-keys: | + license-headers-ce-v1-${{ github.ref_name }}- + license-headers-ce-v1- + - name: Check license headers + env: + # Pull requests check only the files they change; pushes and manual runs check every file. + SINCE: ${{ github.event_name == 'pull_request' && format('origin/{0}', github.base_ref) || '' }} run: | mkdir -p target/license-provenance - ./check-license-headers.sh 2>&1 | tee target/license-provenance/console.log + # The runner does nothing else: use every CPU, not all but one as on a workstation. + LICENSE_HEADERS_JOBS="$(nproc)" + export LICENSE_HEADERS_JOBS + ./check-license-headers.sh ${SINCE:+--since "$SINCE"} 2>&1 | tee target/license-provenance/console.log + + # Saved even when the check finds problems, but only when the run normalized something the cache lacked. + - name: Save normalized CE contents + if: >- + always() && github.event_name != 'pull_request' + && hashFiles('target/license-headers-cache/.updated') != '' + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: target/license-headers-cache + key: license-headers-ce-v1-${{ github.ref_name }}-${{ github.run_id }} - name: Add findings to the job summary if: failure() && hashFiles('target/license-provenance/console.log') != '' diff --git a/check-license-headers.sh b/check-license-headers.sh index 6176d4d7e9..bcfba4f999 100755 --- a/check-license-headers.sh +++ b/check-license-headers.sh @@ -8,9 +8,13 @@ set -euo pipefail usage() { echo "Checks SPDX license headers against CE provenance." - echo "usage: $0 [--fix] [--ce-ref ] [--ce-remote ] [--output target/...]" + echo "usage: $0 [--fix] [--since ] [--ce-ref ] [--ce-remote ] [--output target/...] [--no-cache]" echo " --fix restamp files whose expected header the check determined" echo " and remove redundant or orphaned curations" + echo " --since check only files changed since the merge base of and HEAD," + echo " uncommitted and untracked files included, e.g. --since origin/lts-4.4;" + echo " runs the full check when CE commits, Mycila settings or the check itself changed" + echo " --no-cache normalize every CE file again instead of reusing target/license-headers-cache" echo " --ce-ref CE branch, tag or commit that this branch integrates, fetched on every run;" echo " without it, CE is the history that does not contain the relicensing commit" echo " --ce-remote CE repository to fetch --ce-ref from (default: https://github.com/thingsboard/thingsboard.git)" diff --git a/tools/src/main/python/license-headers/README.md b/tools/src/main/python/license-headers/README.md index 4f2eab2a1e..0c6fb3300f 100644 --- a/tools/src/main/python/license-headers/README.md +++ b/tools/src/main/python/license-headers/README.md @@ -36,7 +36,38 @@ packaging define the new artifact. ./check-license-headers.sh ``` -The check needs the full Git history of the clone. +The check needs the full Git history of the clone. It runs Git and Mycila +subprocesses in parallel on all CPUs but one; set `LICENSE_HEADERS_JOBS` to +another number, for example `1` for a sequential run. + +## Cache + +The check removes the header of every CE file it compares with Mycila. CE files +never change, so their header-free contents are kept in +`target/license-headers-cache` and reused by the next run. The cache is valid +while the Mycila version and configuration in the root `pom.xml`, the templates +and the check itself stay the same; anything else starts a new cache, and the +check normalizes again instead of using the old one. Pass `--no-cache` to +normalize every CE file again, or `--cache` to keep the cache elsewhere. + +In GitHub Actions, pushes and manual runs save the cache and pull requests only +read it: a pull request takes the cache of its base branch, then of `master`. + +## Check only changed files + +```sh +./check-license-headers.sh --since origin/lts-4.4 +``` + +Checks the files that differ between the merge base of the given ref and HEAD +and the working tree, untracked files included, and the files whose curation +changed. Pull requests run the check this way against their target branch; +pushes and manual runs check every file. Curations of files no longer in scope +are still reported for the whole repository. + +The check falls back to every file when a change can move the verdict of an +unchanged file: new CE commits merged into the branch, a changed Mycila +configuration in the root `pom.xml`, or a change to the check itself. ## Fix automatically diff --git a/tools/src/main/python/license-headers/check_license_headers.py b/tools/src/main/python/license-headers/check_license_headers.py index 1ff6faf77c..ec520d9fb9 100644 --- a/tools/src/main/python/license-headers/check_license_headers.py +++ b/tools/src/main/python/license-headers/check_license_headers.py @@ -9,17 +9,21 @@ from __future__ import annotations import argparse from collections import Counter, defaultdict +from concurrent.futures import ThreadPoolExecutor from contextlib import contextmanager from copy import deepcopy from dataclasses import dataclass import hashlib +import io import json import os from pathlib import Path, PurePosixPath import re +import sqlite3 import subprocess import sys import tempfile +import threading import uuid import xml.etree.ElementTree as ET @@ -45,6 +49,7 @@ RELICENSING_COMMIT = "31936b09d24871e421f212502a8342f9d8aabb20" CE_REMOTE = "https://github.com/thingsboard/thingsboard.git" CURATIONS = "tools/src/main/python/license-headers/curations.json" README = "tools/src/main/python/license-headers/README.md" +CHECKER_PATHS = ("tools/src/main/python/license-headers/", "check-license-headers.sh") CURATION_FIELDS = {"path", "contentHash", "header", "reason"} CONTENT_HASH = re.compile(r"sha256:[0-9a-f]{64}") UNRECOGNIZED = "unrecognized" @@ -65,6 +70,11 @@ RESTAMP_LISTING = 40 REPEATED_HEADERS = 3 HEADER_WINDOW = 4096 XML_SPACE = "{http://www.w3.org/XML/1998/namespace}space" +JOBS_VARIABLE = "LICENSE_HEADERS_JOBS" +CACHE_DIRECTORY = "target/license-headers-cache" +CACHE_FORMAT = "1" +CACHE_UPDATED = ".updated" +CACHE_SIGNATURES_KEPT = 3 @dataclass(frozen=True) @@ -132,6 +142,26 @@ class Console: console = Console() +def jobs(): + """Parallel subprocesses: LICENSE_HEADERS_JOBS when set, otherwise all CPUs but one to keep the machine responsive.""" + configured = os.environ.get(JOBS_VARIABLE, "") + if configured: + if not configured.isdigit() or int(configured) < 1: + raise Failure(f"{JOBS_VARIABLE} must be a positive number, not {configured!r}") + return int(configured) + return max(1, (os.cpu_count() or 1) - 1) + + +def parallel(function, items): + """Results of function for every item in item order; the first failure propagates.""" + items = list(items) + workers = min(len(items), jobs()) + if workers <= 1: + return [function(item) for item in items] + with ThreadPoolExecutor(max_workers=workers) as pool: + return list(pool.map(function, items)) + + def run(argv, cwd, *, data=None, ok=(0,)): result = subprocess.run(argv, cwd=cwd, input=data, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if result.returncode not in ok: @@ -238,9 +268,12 @@ class Change: status: str -def history(repo, revision, *options): +def history(repo, revisions, *options): + """First-parent changes of every revision in one walk: commits shared by several revisions appear once.""" + if not revisions or any(revision.startswith("-") for revision in revisions): + raise Failure("history needs revisions that do not start with '-'") raw = git(repo, "log", "--first-parent", "--diff-merges=first-parent", "--root", "--raw", "--no-abbrev", - "--no-renames", "-z", "--format=%x1e%H", *options, revision, "--") + "--no-renames", "-z", "--format=%x1e%H", *options, *revisions, "--") return list(parse_history(raw)) @@ -400,8 +433,8 @@ def validate_curation(entry): return name -def xml_plain(path): - root = ET.parse(path).getroot() +def xml_plain(source): + root = ET.parse(source).getroot() for element in root.iter(): element.tag = element.tag.rsplit("}", 1)[-1] return root @@ -418,7 +451,15 @@ class Plugin: def read_plugin(repo): - plugins = xml_plain(repo / "pom.xml").findall("./build/pluginManagement/plugins/plugin") + return parse_plugin(xml_plain(repo / "pom.xml")) + + +def plugin_signature(plugin): + return plugin.version, ET.tostring(plugin.configuration) + + +def parse_plugin(project): + plugins = project.findall("./build/pluginManagement/plugins/plugin") plugin = next((p for p in plugins if p.findtext("artifactId") == "license-maven-plugin"), None) if plugin is None: raise Failure("Root pom.xml does not manage the Mycila license plugin") @@ -451,8 +492,8 @@ class Scope: def discover_scope(repo, plugin): states = defaultdict(set) modules = [] - for entry in SCOPE_POMS: - for report in scope_check(repo, plugin, entry): + for reports in parallel(lambda entry: scope_check(repo, plugin, entry), SCOPE_POMS): + for report in reports: module = report.parent.parent modules.append({"path": str(module.relative_to(repo)), "report": str(report.relative_to(repo))}) for name, result in read_scope_report(repo, module, report): @@ -516,7 +557,6 @@ class Mycila: def __init__(self, repo, directory, plugin): self.root = directory self.plugin = plugin - self.report = directory / "report.json" self.paths = {} self.contents = {} self.removed = {} @@ -527,9 +567,10 @@ class Mycila: (directory / name).parent.mkdir(parents=True, exist_ok=True) (directory / name).write_bytes(self.templates[header]) - def add(self, key, name, content): + def add(self, key, name, content, slot=None): group = "head" if key[0] == "head" else "ce" - path = self.root / "files" / group / str(len(self.paths)) / PurePosixPath(name).name + slot = len(self.paths) if slot is None else slot + path = self.root / "files" / group / str(slot) / PurePosixPath(name).name path.parent.mkdir(parents=True) path.write_bytes(content) self.paths[key] = path.relative_to(self.root).as_posix() @@ -548,8 +589,9 @@ class Mycila: def current_headers(self, keys): keys = list(keys) recognized = defaultdict(list) - for header in TEMPLATES: - for key, result in self.invoke("check", header, keys).items(): + checks = parallel(lambda header: self.invoke("check", header, keys), TEMPLATES) + for header, results in zip(TEMPLATES, checks): + for key, result in results.items(): if result == "PRESENT": recognized[key].append(header) return {key: recognized[key][0] if len(recognized[key]) == 1 else UNRECOGNIZED for key in keys} @@ -631,43 +673,46 @@ class Mycila: rejected[key] = "more than one header, review by hand" accepted = [key for key in keys if key not in rejected] with self.guarded(accepted): - for header in TEMPLATES: - group = [key for key in accepted if expected[key] == header] - if group: - self.invoke("format", header, group) + groups = {header: [key for key in accepted if expected[key] == header] for header in TEMPLATES} + parallel(lambda header: self.invoke("format", header, groups[header]), TEMPLATES) return {key: self.contents[key] for key in accepted}, rejected def invoke(self, goal, header, keys, *, styles=()): keys = list(keys) if not keys: return {} - self.write_pom(header, keys, styles) - self.report.unlink(missing_ok=True) + invocation = uuid.uuid4().hex + pom, report = self.root / f"pom-{invocation}.xml", self.root / f"report-{invocation}.json" + self.write_pom(pom, report, header, keys, styles) try: - maven(self.root, [self.plugin.coordinates + ":" + goal]) + maven(self.root, ["-f", pom.name, self.plugin.coordinates + ":" + goal]) + results = self.read_results(report) except Failure as exc: - unknown = self.unknown_inputs(keys) + unknown = self.unknown_inputs(report, keys) if unknown: raise Failure(f"Mycila cannot normalize these inputs: {unknown[:20]}") from exc raise - results = self.read_results() + finally: + pom.unlink(missing_ok=True) + report.unlink(missing_ok=True) if set(results) != {self.paths[key] for key in keys} or "UNKNOWN" in results.values(): raise Failure("Mycila comparison scope was incomplete or unknown") return {key: results[self.paths[key]] for key in keys} - def read_results(self): - if not self.report.exists(): + @staticmethod + def read_results(report): + if not report.exists(): raise Failure("Mycila did not produce its comparison report") - return {item["path"]: item["result"] for item in json.loads(self.report.read_text())["files"]} + return {item["path"]: item["result"] for item in json.loads(report.read_text())["files"]} - def unknown_inputs(self, keys): + def unknown_inputs(self, report, keys): try: - results = self.read_results() + results = self.read_results(report) except Failure: return [] return [str(key) for key in keys if results.get(self.paths[key]) == "UNKNOWN"] - def write_pom(self, header, keys, styles): + def write_pom(self, pom, report, header, keys, styles): project = ET.Element("project", xmlns="http://maven.apache.org/POM/4.0.0") append_elements(project, [("modelVersion", "4.0.0"), ("groupId", "license.provenance"), ("artifactId", "temporary-comparison"), ("version", "1")]) @@ -677,7 +722,7 @@ class Mycila: config = ET.SubElement(plugin, "configuration") append_elements(config, [("encoding", "UTF-8"), ("strictCheck", "true"), ("quiet", "true"), ("failIfMissing", "false"), ("failIfUnknown", "true"), - ("reportFormat", "json"), ("reportLocation", str(self.report))]) + ("reportFormat", "json"), ("reportLocation", str(report))]) config.append(self.mapping(styles)) license_set = ET.SubElement(ET.SubElement(config, "licenseSets"), "licenseSet") append_elements(license_set, [("header", str(self.root / TEMPLATES[header])), @@ -688,7 +733,7 @@ class Mycila: parent = ET.SubElement(license_set, "inlineHeaderStyles") for style in styles: append_elements(ET.SubElement(parent, "inlineHeaderStyle"), (("name", style.name),) + style.settings) - ET.ElementTree(project).write(self.root / "pom.xml", encoding="utf-8", xml_declaration=True) + ET.ElementTree(project).write(pom, encoding="utf-8", xml_declaration=True) def mapping(self, styles): mapping = self.plugin.configuration.find("mapping") @@ -822,9 +867,8 @@ class Lineage: if git(repo, "rev-parse", "--is-shallow-repository").decode().strip() == "true": raise Failure("this clone is shallow and the check needs full history. Run git fetch --unshallow.") deleted = {} - for base in bases: - for change in history(repo, base, "--diff-filter=D"): - deleted.setdefault(change.path, {"path": change.path, "ref": change.commit + "^1", "blob": change.old}) + for change in history(repo, list(bases), "--diff-filter=D"): + deleted.setdefault(change.path, {"path": change.path, "ref": change.commit + "^1", "blob": change.old}) return cls(head=head, bases=tuple(bases), trees={base: tree(repo, base) for base in bases}, deleted=deleted) def versions(self, name): @@ -867,7 +911,116 @@ class Comparison: )) -def compare(repo, plugin, lineage, contents): +class NormalizationCache: + """Header-free contents of CE inputs from earlier runs, keyed by content and file name (Mycila styles follow the + name). One SQLite file per normalization signature: a different Mycila setup, template or check misses the cache.""" + + def __init__(self, directory, signature): + self.directory = directory + self.lock = threading.Lock() + self.added = 0 + self.hits = 0 + directory.mkdir(parents=True, exist_ok=True) + (directory / CACHE_UPDATED).unlink(missing_ok=True) + self.path = directory / f"{signature}.sqlite" + try: + self.database = self.open() + except sqlite3.DatabaseError: + # A damaged cache only costs time: start it again instead of failing the check. + self.path.unlink() + self.database = self.open() + os.utime(self.path) + for stale in sorted(directory.glob("*.sqlite"), key=lambda path: path.stat().st_mtime)[:-CACHE_SIGNATURES_KEPT]: + stale.unlink() + + def open(self): + database = sqlite3.connect(self.path, check_same_thread=False) + database.execute("CREATE TABLE IF NOT EXISTS normalized (input TEXT PRIMARY KEY, content BLOB NOT NULL)") + return database + + @staticmethod + def input(name, raw): + return hashlib.sha256(raw).hexdigest() + "/" + PurePosixPath(name).name + + def get(self, inputs): + found = {} + with self.lock: + for key, raw in inputs.items(): + row = self.database.execute("SELECT content FROM normalized WHERE input = ?", + (self.input(key[0], raw),)).fetchone() + if row is not None: + found[key] = bytes(row[0]) + self.hits += len(found) + return found + + def put(self, entries): + with self.lock: + self.database.executemany("INSERT OR IGNORE INTO normalized VALUES (?, ?)", + [(self.input(key[0], raw), content) for key, raw, content in entries]) + self.added += len(entries) + + def close(self): + self.database.commit() + self.database.close() + if self.added: + (self.directory / CACHE_UPDATED).touch() + + +class NoCache: + added = hits = 0 + + def get(self, inputs): + return {} + + def put(self, entries): + pass + + def close(self): + pass + + +def cache_signature(repo, plugin): + digest = hashlib.sha256(CACHE_FORMAT.encode()) + version, configuration = plugin_signature(plugin) + for part in (Path(__file__).read_bytes(), version.encode(), configuration, + *((repo / name).read_bytes() for name in TEMPLATES.values())): + digest.update(len(part).to_bytes(8, "big") + part) + return digest.hexdigest()[:32] + + +def normalize(repo, plugin, cache, inputs): + """Header-free contents of CE inputs ({key: raw bytes}, key[0] the file name), from the cache when it has them.""" + found = cache.get(inputs) + missing = {key: raw for key, raw in inputs.items() if key not in found} + if missing: + with tempfile.TemporaryDirectory(prefix="license-provenance-") as temporary: + mycila = Mycila(repo, Path(temporary), plugin) + for key, raw in missing.items(): + mycila.add(key, key[0], raw) + mycila.strip_headers() + grown = [key[0] for key, raw in missing.items() if len(mycila.contents[key]) > len(raw)] + if grown: + raise Failure(f"Mycila grew these files while removing their headers: {grown[:20]}") + found |= {key: mycila.contents[key] for key in missing} + cache.put([(key, raw, found[key]) for key, raw in missing.items()]) + return found + + +def staged_size(content): + return len(content.replace(b"\r\n", b"\n")) + + +def could_be_copy(size, destinations): + """Git scores a pair 0 unless the smaller blob is at least half the larger (diffcore-rename estimate_similarity).""" + return any(2 * min(size, other) >= max(size, other) for other in destinations) + + +def could_shrink_to_copy(raw_size, destinations): + """Normalizing never grows a file: below half the smallest destination it stays out of Git's reach.""" + return 2 * raw_size >= min(destinations) + + +def compare(repo, plugin, lineage, contents, cache): names = list(contents) new_paths = {name for name in names if not lineage.versions(name)} sources = {} @@ -877,22 +1030,32 @@ def compare(repo, plugin, lineage, contents): sources.setdefault((name, files[name]), base) for key in comparable_ce_files(files, new_paths).items(): sources.setdefault(key, base) + versions = {(name, oid) for name in names for _, oid in lineage.versions(name)} + # Every input keeps the slot it has among all inputs, so the copy search sees the same paths, and Git breaks + # ties between equally similar sources the same way, however many sources the size filter drops. + slots = {("head", name): index for index, name in enumerate(names)} + slots |= {key: len(names) + index for index, key in enumerate(sorted(sources))} bytes_by_id = blobs(repo, [oid for _, oid in sources]) with tempfile.TemporaryDirectory(prefix="license-provenance-") as temporary: mycila = Mycila(repo, Path(temporary), plugin) for name, content in contents.items(): - mycila.add(("head", name), name, content) - for path, oid in sorted(sources): - mycila.add((path, oid), path, bytes_by_id[oid]) + mycila.add(("head", name), name, content, slots[("head", name)]) console.begin("Recognizing headers") recognized = mycila.current_headers([("head", name) for name in names]) console.end() console.begin("Comparing against CE") - normalized = mycila.strip_headers() + head_hashes, copy_sources = parallel(lambda job: job(), [ + mycila.strip_headers, + lambda: normalize(repo, plugin, cache, {key: bytes_by_id[key[1]] for key in versions})]) headers = mycila.header_states(recognized) - copies = normalized_copies(mycila, sources, new_paths, mycila.nonempty()) - merges = clean_merges(repo, plugin, lineage, names, normalized) - console.end(f"done ({len(normalized)} file versions)") + destinations = {name: mycila.contents[("head", name)] for name in sorted(new_paths) + if mycila.contents[("head", name)].strip()} + normalized = head_hashes | {key: comparison_hash(content) for key, content in copy_sources.items()} + copies, searched = copy_candidates(repo, plugin, cache, sources, versions, slots, bytes_by_id, + destinations, copy_sources, normalized) + merges = clean_merges(repo, plugin, cache, lineage, names, normalized) + console.end(f"done ({len(normalized)} file versions, {searched} of {len(sources) - len(versions)} " + f"other CE files searched for copies, {cache.hits} from the cache)") return Comparison( lineage=lineage, contents=contents, @@ -905,31 +1068,57 @@ def compare(repo, plugin, lineage, contents): ) -def clean_merges(repo, plugin, lineage, names, normalized): - merged = {} - for index, left in enumerate(lineage.bases): - for right in lineage.bases[index + 1:]: - ancestors = git(repo, "merge-base", "--all", left, right).decode().split() - if len(ancestors) != 1: +def copy_candidates(repo, plugin, cache, sources, versions, slots, bytes_by_id, destinations, copy_sources, + normalized): + """CE files similar to the paths that CE does not have, normalized only when Git could match them by size.""" + if not destinations: + return {}, 0 + sizes = [staged_size(content) for content in destinations.values()] + others = sorted(key for key in sources if key not in versions + and could_shrink_to_copy(len(bytes_by_id[key[1]]), sizes)) + found = normalize(repo, plugin, cache, {key: bytes_by_id[key[1]] for key in others}) + normalized |= {key: comparison_hash(content) for key, content in found.items()} + with tempfile.TemporaryDirectory(prefix="license-provenance-") as temporary: + staging = Mycila(repo, Path(temporary), plugin) + for key, content in (found | copy_sources).items(): + staging.add(key, key[0], content, slots[key]) + for name, content in destinations.items(): + staging.add(("head", name), name, content, slots[("head", name)]) + reachable = {key: sources[key] for key in [*others, *copy_sources] + if could_be_copy(staged_size(staging.contents[key]), sizes)} + return normalized_copies(staging, reachable, set(destinations), staging.nonempty()), len(others) + + +def clean_merges(repo, plugin, cache, lineage, names, normalized): + pairs = [(left, right) for index, left in enumerate(lineage.bases) for right in lineage.bases[index + 1:]] + + def ancestry(pair): + ancestors = git(repo, "merge-base", "--all", *pair).decode().split() + return (ancestors[0], tree(repo, ancestors[0])) if len(ancestors) == 1 else None + + candidates = [] + for (left, right), common in zip(pairs, parallel(ancestry, pairs)): + if common is None: + continue + ancestor, files = common + for name in names: + ours, theirs = lineage.trees[left].get(name), lineage.trees[right].get(name) + if ours is None or theirs is None or ours == theirs or name not in files: + continue + if normalized[("head", name)] in {normalized[(name, ours)], normalized[(name, theirs)]}: continue - ancestry = tree(repo, ancestors[0]) - for name in names: - ours, theirs = lineage.trees[left].get(name), lineage.trees[right].get(name) - if ours is None or theirs is None or ours == theirs or name not in ancestry: - continue - if normalized[("head", name)] in {normalized[(name, ours)], normalized[(name, theirs)]}: - continue - content = merge_blobs(repo, ours, ancestry[name], theirs) - if content is not None: - merged[(name, left, right)] = (content, {"path": name, "merge": [left, right], - "base": ancestors[0]}) + candidates.append(((name, left, right), (ours, files[name], theirs), ancestor)) + # Base pairs share most blobs: every distinct three-way merge runs once, all of them in parallel. + triples = list(dict.fromkeys(triple for _, triple, _ in candidates)) + contents = dict(zip(triples, parallel(lambda triple: merge_blobs(repo, *triple), triples))) + merged = {} + for key, triple, ancestor in candidates: + if contents[triple] is not None: + merged[key] = (contents[triple], {"path": key[0], "merge": [key[1], key[2]], "base": ancestor}) if not merged: return {} - with tempfile.TemporaryDirectory(prefix="license-provenance-") as temporary: - mycila = Mycila(repo, Path(temporary), plugin) - for key, (content, _) in merged.items(): - mycila.add(key, key[0], content) - hashes = mycila.strip_headers() + found = normalize(repo, plugin, cache, {key: content for key, (content, _) in merged.items()}) + hashes = {key: comparison_hash(content) for key, content in found.items()} result = {} for key, (_, description) in merged.items(): if hashes[key] == normalized[("head", key[0])]: @@ -937,6 +1126,85 @@ def clean_merges(repo, plugin, lineage, names, normalized): return result +@dataclass(frozen=True) +class Selection: + since: str + merge_base: str + paths: frozenset | None + reason: str + + @property + def full(self): + return self.paths is None + + def report(self): + return {"since": self.since, "mergeBase": self.merge_base, "full": self.full, "reason": self.reason} + + +def merge_base(repo, since): + commit = resolve(repo, since) + bases = run(["git", "merge-base", commit, "HEAD"], repo, ok=(0, 1)).stdout.decode().split() + if not bases: + raise Failure(f"HEAD shares no history with {since}.") + return bases[0] + + +def changed_paths(repo, commit): + """Paths that differ between the commit and the working tree, untracked files included.""" + tracked = git(repo, "diff", "--name-only", "--no-renames", "-z", commit, "--") + untracked = git(repo, "ls-files", "--others", "--exclude-standard", "-z") + return {path.decode("utf-8") for path in (tracked + b"\0" + untracked).split(b"\0") if path} + + +def committed(repo, commit, name): + result = run(["git", "cat-file", "blob", f"{commit}:{name}"], repo, ok=(0, 128)) + return result.stdout if result.returncode == 0 else None + + +def committed_plugin(repo, commit): + content = committed(repo, commit, "pom.xml") + try: + return None if content is None else plugin_signature(parse_plugin(xml_plain(io.BytesIO(content)))) + except (Failure, ET.ParseError): + return None + + +def committed_curations(repo, commit): + content = committed(repo, commit, CURATIONS) + if content is None: + return {} + try: + return {entry["path"]: entry for entry in json.loads(content)["curations"]} + except (ValueError, KeyError, TypeError): + return None + + +def select_changes(repo, since, bases, ce_bases, plugin, curations): + """Files to check against a PR target: the changed ones, unless a change can move verdicts of unchanged files.""" + base = merge_base(repo, since) + + def full(reason): + return Selection(since, base, None, reason) + + try: + if sorted(ce_bases(base)) != sorted(bases): + return full("the CE commits merged into the branch changed") + except Failure: + return full("the CE commits merged at the merge base cannot be resolved") + if committed_plugin(repo, base) != plugin_signature(plugin): + return full("the Mycila configuration in the root pom.xml changed") + changed = changed_paths(repo, base) + checker = sorted(path for path in changed + if path.startswith(CHECKER_PATHS) and path not in {CURATIONS, README}) + if checker: + return full(f"the check itself changed ({checker[0]})") + previous = committed_curations(repo, base) + curated = set(curations) if previous is None else { + name for name in set(previous) | set(curations) if previous.get(name) != curations.get(name)} + paths = frozenset(changed | curated) + return Selection(since, base, paths, f"{len(paths)} changed paths") + + def current_branch(repo): branch = git(repo, "rev-parse", "--abbrev-ref", "HEAD").decode().strip() return "" if branch == "HEAD" else branch @@ -1058,15 +1326,19 @@ def print_findings(rows, curation_issues, ref_names): f"Rerun with --fix to remove them from {CURATIONS}", style=None) -def print_summary(rows, curation_issues, report): +def print_summary(rows, curation_issues, report, label="files"): findings = sum(row["status"] != "match" for row in rows) + len(curation_issues) restamped = sum("previousHeader" in row for row in rows) note = f" ({restamped} restamped)" if restamped else "" if findings: - console.line(f"{findings} finding{'s' if findings != 1 else ''} in {len(rows)} files{note}. Report: {report}", + console.line(f"{findings} finding{'s' if findings != 1 else ''} in {len(rows)} {label}{note}. Report: {report}", "red") return - console.line(f"All {len(rows)} files carry the expected header{note}.", "green") + if not rows: + console.line(f"No {label} to check.", "green") + console.line(f"Report: {report}") + return + console.line(f"All {len(rows)} {label} carry the expected header{note}.", "green") counts = Counter(row["expectedHeader"] for row in rows) console.line(" " + " · ".join(f"{header} {counts[header]}" for header in TEMPLATES if counts[header])) console.line(f"Report: {report}") @@ -1166,16 +1438,37 @@ def check(args): curation_bytes = curation_path.read_bytes() curations = load_curations(curation_path) console.begin("Resolving Git history") - bases = merged_ce_bases(repo, head, ce["commit"]) if "ref" in ce else relicensed_ce_bases(repo, head) + + def ce_bases(commit): + return merged_ce_bases(repo, commit, ce["commit"]) if "ref" in ce else relicensed_ce_bases(repo, commit) + + bases = ce_bases(head) lineage = Lineage.load(repo, head, bases) console.end("done (CE base " + ", ".join(ref_name(base, ref_names) for base in bases) + ")") + selection = None + if args.since: + console.begin(f"Selecting files changed since {args.since}") + selection = select_changes(repo, args.since, bases, ce_bases, plugin, curations) + console.end(("full check: " if selection.full else "") + selection.reason + + f" (merge base {selection.merge_base[:11]})") console.begin("Collecting Mycila scope") scope = discover_scope(repo, plugin) console.end(f"{len(scope.eligible)} files ({scope.ignored} Git-ignored skipped)") - contents = {name: (repo / name).read_bytes() for name in scope.eligible} - comparison = compare(repo, plugin, lineage, contents) + checked = (scope.eligible if selection is None or selection.full + else [name for name in scope.eligible if name in selection.paths]) + if selection is not None and not selection.full: + console.line(f"Checking {len(checked)} of {len(scope.eligible)} files in scope", "dim") + contents = {name: (repo / name).read_bytes() for name in checked} + rows = [] + if contents: + cache = (NoCache() if args.no_cache + else NormalizationCache((repo / args.cache).resolve(), cache_signature(repo, plugin))) + try: + comparison = compare(repo, plugin, lineage, contents, cache) + finally: + cache.close() + rows = [comparison.classify(name, curations.get(name)) for name in checked] console.line() - rows = [comparison.classify(name, curations.get(name)) for name in scope.eligible] orphaned = [{"path": name, "status": "stale-curation", "reason": "file is no longer in scope"} for name in sorted(set(curations) - set(scope.eligible))] ensure_inputs_unchanged(repo, lineage, curation_path, curation_bytes, contents) @@ -1190,6 +1483,7 @@ def check(args): "head": lineage.head, "ce": ce | {"bases": list(lineage.bases)}, "scope": {"supported": len(scope.eligible), "unknown": scope.unknown, "modules": scope.modules}, + "selection": selection.report() if selection is not None else None, "summary": dict(summary), "restamped": sorted(row["path"] for row in rows if "previousHeader" in row), "removedCurations": removed, @@ -1203,7 +1497,7 @@ def check(args): print_restamped(rows) print_removed_curations(removed) print_findings(rows, orphaned, ref_names) - print_summary(rows, orphaned, report) + print_summary(rows, orphaned, report, "files" if selection is None or selection.full else "changed files") return 1 if orphaned or summary.keys() - {"match"} else 0 @@ -1215,7 +1509,15 @@ def main(argv=None): "without it, CE is the history of HEAD that does not contain the relicensing commit") parser.add_argument("--ce-remote", default=CE_REMOTE, help=f"Git URL or path of the CE repository to fetch --ce-ref from (default: {CE_REMOTE})") + parser.add_argument("--since", metavar="REF", + help="check only files changed since the merge base of REF and HEAD, uncommitted and " + "untracked files included; falls back to the full check when the CE commits, the " + "root Mycila configuration or the check itself changed") parser.add_argument("--output", default="target/license-provenance/report.json") + parser.add_argument("--cache", default=CACHE_DIRECTORY, metavar="DIRECTORY", + help="header-free CE contents from earlier runs, reused while the Mycila setup, the " + f"templates and the check stay the same (default: {CACHE_DIRECTORY})") + parser.add_argument("--no-cache", action="store_true", help="normalize every CE input again") parser.add_argument("--fix", action="store_true", help="restamp files whose expected header the check determined and remove redundant or " "orphaned curations; unrecognized headers are kept") diff --git a/tools/src/main/python/license-headers/test_check_license_headers.py b/tools/src/main/python/license-headers/test_check_license_headers.py index a025443e75..0756cc41bd 100644 --- a/tools/src/main/python/license-headers/test_check_license_headers.py +++ b/tools/src/main/python/license-headers/test_check_license_headers.py @@ -240,6 +240,57 @@ class DecisionTests(unittest.TestCase): stderr.getvalue()) +class ParallelTests(unittest.TestCase): + def test_jobs_follow_the_machine_unless_configured(self): + for cpus, expected in ((12, 11), (2, 1), (1, 1), (None, 1)): + with patch.dict(os.environ, {p.JOBS_VARIABLE: ""}), patch.object(p.os, "cpu_count", return_value=cpus): + self.assertEqual(expected, p.jobs(), f"{cpus} CPUs") + with patch.dict(os.environ, {p.JOBS_VARIABLE: "3"}): + self.assertEqual(3, p.jobs()) + for wrong in ("0", "-2", "many"): + with patch.dict(os.environ, {p.JOBS_VARIABLE: wrong}), self.assertRaisesRegex(p.Failure, p.JOBS_VARIABLE): + p.jobs() + + def test_parallel_keeps_item_order_and_raises_the_first_failure(self): + with patch.dict(os.environ, {p.JOBS_VARIABLE: "4"}): + self.assertEqual([item * 2 for item in range(50)], p.parallel(lambda item: item * 2, range(50))) + self.assertEqual([], p.parallel(lambda item: item, [])) + + def failing(item): + if item == 7: + raise p.Failure("item 7") + return item + + with self.assertRaisesRegex(p.Failure, "item 7"): + p.parallel(failing, range(20)) + + +class MycilaGuardTests(unittest.TestCase): + def tool(self): + tool = p.Mycila(this_repository(), temporary_directory(self), fixture_plugin()) + tool.add(("head", "A.java"), "A.java", b"// header\ncode") + return tool + + def test_guard_restores_the_file_end_and_rejects_a_rewritten_one(self): + tool = self.tool() + with tool.guarded([("head", "A.java")]): + tool.file(("head", "A.java")).write_bytes(tool.file(("head", "A.java")).read_bytes().replace(b"// header\n", b"")) + self.assertEqual(b"code", tool.contents[("head", "A.java")]) + with self.assertRaisesRegex(p.Failure, "Mycila rewrote the end"): + with tool.guarded([("head", "A.java")]): + tool.file(("head", "A.java")).write_bytes(b"code\n") + + def test_scope_reports_are_accepted_only_from_target_directories(self): + repo = temporary_directory(self) + (repo / "module/target").mkdir(parents=True) + (repo / "module/target/token.json").write_text("{}") + self.assertEqual([repo / "module/target/token.json"], p.scope_reports(repo, "token.json")) + (repo / "other").mkdir() + (repo / "other/token.json").write_text("{}") + with self.assertRaisesRegex(p.Failure, "Unexpected scope report location"): + p.scope_reports(repo, "token.json") + + class InputTests(unittest.TestCase): def test_header_state_recognizes_legacy_thingsboard_headers(self): ce = b"/**\n * Copyright \xc2\xa9 2016-2025 The Thingsboard Authors\n *\n * Licensed under the Apache License\n */\n" @@ -270,6 +321,8 @@ class InputTests(unittest.TestCase): self.assertEqual(b"// SPDX-A\n// SPDX-B", p.swap_header(b"// SPDX-X\n// SPDX-Y\n// SPDX-Z", new, old)) with self.assertRaises(p.Failure): p.swap_header(b"// SPDX-A\n\n// SPDX-B\ncode\n", old, new) + with self.assertRaises(p.Failure): + p.swap_header(b"// SPDX-A\n# SPDX-B\ncode\n", old, new) with self.assertRaises(p.Failure): p.swap_header(b"code\n", old, new) @@ -355,6 +408,30 @@ class InputTests(unittest.TestCase): self.assertEqual(f"{p.TEMPLATE_DIRECTORY}/license-header-{p.NON_CE}.txt", p.TEMPLATES[p.NON_CE]) self.assertTrue((this_repository() / p.TEMPLATES[p.NON_CE]).is_file()) + def test_committed_plugin_tracks_the_root_mycila_configuration(self): + git = GitFixture(temporary_directory(self), "main") + + def pom(header): + return textwrap.dedent(f"""\ + + com.mycilalicense-maven-plugin5.1.2 +
{header}
+
+ """) + + git.write("pom.xml", pom("a.txt")) + first = git.commit("pom") + git.write("pom.xml", "\n" + pom("a.txt")) + same = git.commit("comment only") + git.write("pom.xml", pom("b.txt")) + changed = git.commit("other header") + current = p.plugin_signature(p.read_plugin(git.root)) + self.assertEqual(p.committed_plugin(git.root, first), p.committed_plugin(git.root, same)) + self.assertNotEqual(p.committed_plugin(git.root, same), current) + self.assertEqual(p.committed_plugin(git.root, changed), current) + git("rm", "-q", "pom.xml") + self.assertIsNone(p.committed_plugin(git.root, git.commit("no pom"))) + def test_plugin_version_and_configuration_come_from_root_pom(self): repo = temporary_directory(self) p.git(repo, "init") @@ -390,13 +467,13 @@ class GitHistoryTests(unittest.TestCase): git("checkout", "lts-4.2") git("merge", "--no-ff", "side", "-m", "integrate") merged = git("rev-parse", "HEAD") - changes = p.history(git.root, "HEAD") + changes = p.history(git.root, ["HEAD"]) self.assertEqual({initial, merged}, {change.commit for change in changes}) self.assertEqual(source, changes[0].path) git("rm", source) git.commit("delete") - deleted = p.history(git.root, "HEAD", "--diff-filter=D") + deleted = p.history(git.root, ["HEAD"], "--diff-filter=D") self.assertEqual(["D"], [change.status for change in deleted]) self.assertEqual(b"merged result\n", p.blobs(git.root, [deleted[0].old])[deleted[0].old]) @@ -491,6 +568,71 @@ class GitHistoryTests(unittest.TestCase): self.assertEqual([(removal, git("rev-parse", f"{removal}:Kept.java"))], lineage.versions("Kept.java")) self.assertEqual([], lineage.versions("Gone.java")) + def test_lineage_walks_shared_history_of_several_bases_once(self): + git = GitFixture(temporary_directory(self), "ce") + git.write("Shared.java", "deleted before the bases diverged\n") + git.write("Left.java", "deleted on the left base\n") + git.write("Right.java", "deleted on the right base\n") + git.commit("CE base") + git("rm", "Shared.java") + shared = git.commit("shared removal") + git("checkout", "-b", "right") + git("rm", "Right.java") + right = git.commit("right removal") + git("checkout", "ce") + git("rm", "Left.java") + left = git.commit("left removal") + separately = {} + for base in (left, right): + for change in p.history(git.root, [base], "--diff-filter=D"): + separately.setdefault(change.path, set()).add(change.commit) + together = p.history(git.root, [left, right], "--diff-filter=D") + self.assertEqual(3, len(together), "the shared removal is listed once") + self.assertEqual(separately, {change.path: {change.commit} for change in together}) + lineage = p.Lineage.load(git.root, left, [left, right]) + self.assertEqual({"Shared.java": shared + "^1", "Left.java": left + "^1", "Right.java": right + "^1"}, + {path: entry["ref"] for path, entry in lineage.deleted.items()}) + with self.assertRaises(p.Failure): + p.history(git.root, []) + with self.assertRaises(p.Failure): + p.history(git.root, ["--all"]) + + def test_clean_merges_match_each_file_with_its_own_merge_in_any_order(self): + git = GitFixture(temporary_directory(self), "ce") + for header, name in p.TEMPLATES.items(): + git.write(name, f"fixture {header}\n") + lines = "".join(f"line {index}\n" for index in range(12)) + git.write("A.java", "A\n" + lines) + git.write("B.java", "B\n" + lines) + base = git.commit("CE base") + bases = {} + for branch, line in (("left", "line 0"), ("middle", "line 5"), ("right", "line 11")): + git("checkout", "-q", "-b", branch, base) + git.write("A.java", "A\n" + lines.replace(line, branch)) + git.write("B.java", "B\n" + lines.replace(line, branch)) + bases[branch] = git.commit(branch) + lineage = p.Lineage.load(git.root, bases["left"], sorted(bases.values())) + # HEAD carries A merged from left and right, B merged from middle and right: two distinct merges. + head = {"A.java": "A\n" + lines.replace("line 0", "left").replace("line 11", "right"), + "B.java": "B\n" + lines.replace("line 5", "middle").replace("line 11", "right")} + normalized = {("head", name): p.comparison_hash(text.encode()) for name, text in head.items()} + for files in lineage.trees.values(): + for name, oid in files.items(): + normalized[(name, oid)] = p.comparison_hash(p.blobs(git.root, [oid])[oid]) + + def strip_headers(tool): + return {key: p.comparison_hash(content) for key, content in tool.contents.items()} + + expected = {"A.java": sorted([bases["left"], bases["right"]]), + "B.java": sorted([bases["middle"], bases["right"]])} + with patch.object(p.Mycila, "strip_headers", strip_headers): + for workers in ("1", "4"): + with patch.dict(os.environ, {p.JOBS_VARIABLE: workers}): + merges = p.clean_merges(git.root, fixture_plugin(), p.NoCache(), lineage, list(head), normalized) + self.assertEqual(expected, {name: sorted(merge["merge"]) for name, merge in merges.items()}, + f"{workers} workers") + self.assertEqual({base}, {merge["base"] for merge in merges.values()}) + def test_merge_blobs_returns_only_clean_merges(self): git = GitFixture(temporary_directory(self), "main") git.write("File.java", "one\ntwo\nthree\nfour\nfive\n") @@ -569,6 +711,10 @@ class FetchTests(unittest.TestCase): third = self.ce.commit("third") self.assertEqual(third, self.fetch("lts-4.2")) + def test_a_local_branch_of_the_same_name_does_not_shadow_the_fetched_tip(self): + self.local("branch", "lts-4.2") + self.assertEqual(self.second, self.fetch("lts-4.2")) + def test_missing_ref_and_option_like_ref_are_rejected(self): with self.assertRaisesRegex(p.Failure, r"(?s)cannot fetch 'missing' from .*couldn't find remote ref missing"): self.fetch("missing") @@ -609,7 +755,7 @@ class CheckCommandTests(unittest.TestCase): self.scope = ["Base.java", "Changed.java", "Fixed.java", "Merged.java", "New.java", "Source.java"] self.output = self.repo / "target/report.json" - def check(self, *args, scope=None): + def check(self, *args, scope=None, base_plugin=fixture_plugin(), normalizer=None): def recognized(content): for header in p.TEMPLATES: if content.startswith(fixture(header).encode()): @@ -639,9 +785,10 @@ class CheckCommandTests(unittest.TestCase): with (patch.object(p.Path, "cwd", return_value=self.repo), patch.object(p, "RELICENSING_COMMIT", self.relicensing), patch.object(p, "read_plugin", return_value=fixture_plugin()), + patch.object(p, "committed_plugin", return_value=p.plugin_signature(base_plugin)), patch.object(p, "discover_scope", return_value=p.Scope(scope or self.scope, [], [], 0)), patch.object(p.Mycila, "current_headers", current_headers), - patch.object(p.Mycila, "strip_headers", strip_headers), + patch.object(p.Mycila, "strip_headers", normalizer or strip_headers), patch.object(p.Mycila, "restamp", restamp), redirect_stdout(io.StringIO()), redirect_stderr(stderr)): code = p.main(["check", "--output", str(self.output), *args]) @@ -737,6 +884,116 @@ class CheckCommandTests(unittest.TestCase): code, report, _ = self.check("--fix", scope=scope) self.assertEqual((0, []), (code, report["removedCurations"])) + def pull_request(self): + self.git("checkout", "-q", "-b", "feature") + return self.git("rev-parse", "master") + + def checked(self, report): + return sorted(row["path"] for row in report["files"]) + + def test_files_changed_during_the_scan_fail_the_check(self): + compare = p.compare + + def edit_while_scanning(*args): + result = compare(*args) + self.git.write("Base.java", fixture("apache") + "edited during the scan\n") + return result + + with patch.object(p, "compare", edit_while_scanning): + code, report, output = self.check() + self.assertEqual((2, None), (code, report)) + self.assertIn("changed during the scan", output) + + def test_since_checks_only_changed_and_untracked_files(self): + target = self.pull_request() + self.git.write("New.java", fixture("apache") + "TB feature\n") + self.git.commit("wrong header on a TB file") + self.git.write("Added.java", fixture(p.NON_CE) + "untracked TB file\n") + code, report, output = self.check("--since", "master", scope=self.scope + ["Added.java"]) + self.assertEqual(1, code) + self.assertEqual(["Added.java", "New.java"], self.checked(report)) + self.assertEqual("mismatch", self.rows(report)["New.java"]["status"]) + self.assertEqual({"since": "master", "mergeBase": target, "full": False, "reason": "2 changed paths"}, + report["selection"]) + self.assertEqual(7, report["scope"]["supported"]) + self.assertIn("Checking 2 of 7 files in scope", output) + self.assertIn("1 finding in 2 changed files", output) + + def test_since_without_changes_checks_nothing_but_orphaned_curations(self): + self.pull_request() + code, report, output = self.check("--since", "master") + self.assertEqual((0, []), (code, report["files"])) + self.assertIn("No changed files to check.", output) + orphaned = dict(path="Gone.java", header=p.NON_CE, reason="Reviewed", contentHash=p.raw_hash(b"gone")) + self.git.write(p.CURATIONS, json.dumps(dict(schemaVersion=1, curations=[orphaned]))) + self.git.commit("curation of a file that is not in scope") + code, report, _ = self.check("--since", "master") + self.assertEqual(1, code) + self.assertEqual(["Gone.java"], [issue["path"] for issue in report["curationIssues"]]) + + def test_since_checks_files_whose_curation_changed(self): + curation = dict(path="New.java", header="apache", reason="Reviewed", + contentHash=p.raw_hash((self.repo / "New.java").read_bytes())) + self.git.write(p.CURATIONS, json.dumps(dict(schemaVersion=1, curations=[curation]))) + self.git.commit("curate New.java") + self.pull_request() + self.git.write(p.CURATIONS, json.dumps(dict(schemaVersion=1, curations=[]))) + self.git.commit("drop the curation") + code, report, _ = self.check("--since", "master") + self.assertEqual(0, code) + self.assertEqual(["New.java"], self.checked(report)) + self.assertEqual("not in CE, no CE evidence", self.rows(report)["New.java"]["reason"]) + + def test_since_checks_every_file_when_new_ce_commits_are_merged(self): + self.pull_request() + self.git("checkout", "-q", "lts-4.3") + self.git.write("Fixed.java", fixture("apache") + "second lts addition\n") + self.git.commit("second CE fix") + self.git("checkout", "-q", "feature") + self.git("merge", "-q", "--no-ff", "lts-4.3", "-m", "integrate second CE fix") + code, report, output = self.check("--since", "master") + self.assertEqual(0, code) + self.assertEqual(sorted(self.scope), self.checked(report)) + self.assertEqual("the CE commits merged into the branch changed", report["selection"]["reason"]) + self.assertTrue(report["selection"]["full"]) + self.assertIn("full check: the CE commits merged into the branch changed", output) + + def test_since_checks_every_file_when_the_check_changes(self): + self.pull_request() + self.git.write(p.TEMPLATES["apache"], "fixture apache, reworded\n") + self.git.commit("change a template") + _, report, _ = self.check("--since", "master") + self.assertEqual(sorted(self.scope), self.checked(report)) + self.assertEqual(f"the check itself changed ({p.TEMPLATES['apache']})", report["selection"]["reason"]) + + def test_since_checks_every_file_when_the_mycila_configuration_changes(self): + self.pull_request() + _, report, _ = self.check("--since", "master", base_plugin=fixture_plugin("1")) + self.assertEqual(sorted(self.scope), self.checked(report)) + self.assertEqual("the Mycila configuration in the root pom.xml changed", report["selection"]["reason"]) + + def test_since_does_not_orphan_curations_of_unchanged_files(self): + curation = dict(path="Source.java", header="apache", reason="Reviewed", + contentHash=p.raw_hash((self.repo / "Source.java").read_bytes())) + self.git.write(p.CURATIONS, json.dumps(dict(schemaVersion=1, curations=[curation]))) + self.git.commit("curate Source.java") + self.pull_request() + self.git.write("New.java", fixture(p.NON_CE) + "TB feature, changed\n") + self.git.commit("unrelated change") + code, report, _ = self.check("--since", "master") + self.assertEqual(0, code) + self.assertEqual(["New.java"], self.checked(report)) + self.assertEqual([], report["curationIssues"]) + + def test_since_needs_shared_history(self): + self.git("checkout", "-q", "--orphan", "unrelated") + self.git.write("Other.java", "other\n") + self.git.commit("unrelated") + self.git("checkout", "-q", "master") + code, _, output = self.check("--since", "unrelated") + self.assertEqual(2, code) + self.assertIn("HEAD shares no history with unrelated", output) + def test_missing_relicensing_commit_fails_before_the_scan(self): self.relicensing = "0" * 40 code, report, output = self.check() @@ -886,10 +1143,183 @@ def stamped(header, extension): return text[:-1] if extension in {"java", "ts"} else text +class CopySearchTests(unittest.TestCase): + check = CheckCommandTests.check + rows = CheckCommandTests.rows + BODY = "".join(f" copied statement number {index};\n" for index in range(40)) + + def test_size_filter_follows_git_similarity_threshold(self): + git = GitFixture(temporary_directory(self), "main") + destination = ("".join(f"line {index:04d}\n" for index in range(100))).encode() + half = destination[:len(destination) // 2] + for source, expected in ((half, True), (half[:-1], False)): + self.assertEqual(expected, p.could_be_copy(len(source), [len(destination)])) + tool = p.Mycila.__new__(p.Mycila) + tool.root, tool.paths, tool.contents = git.root, {}, {} + tool.add(("Source.java", "0" * 40), "Source.java", source) + tool.add(("head", "Destination.java"), "Destination.java", destination) + found = p.normalized_copies(tool, {("Source.java", "0" * 40): "ref"}, {"Destination.java"}, + tool.nonempty()) + self.assertEqual(expected, "Destination.java" in found, f"{len(source)} of {len(destination)} bytes") + for path in ("files", ".git"): + p.run(["rm", "-rf", path], git.root) + + def test_filter_before_normalizing_drops_exactly_the_unreachable_sources(self): + # Normalizing removes a header and never grows a file: a source of raw size r can end up at any size up to r. + for destinations in ([7], [7, 30], [30, 7], [12, 13, 60]): + for raw in range(1, 70): + reachable = any(p.could_be_copy(size, destinations) for size in range(1, raw + 1)) + self.assertEqual(reachable, p.could_shrink_to_copy(raw, destinations), f"{raw} → {destinations}") + + def setUp(self): + self.repo = temporary_directory(self) + self.git = git = GitFixture(self.repo, "master") + git.write(".gitignore", "target/\n") + for category, name in p.TEMPLATES.items(): + git.write(name, f"fixture {category}\n") + git.write(p.CURATIONS, '{"schemaVersion": 1, "curations": []}') + # Sorted CE sources: a/ (small), b/Alpha, c/ (small), e/Gamma. Among all inputs Gamma takes slot 12 and + # Alpha slot 3, so Gamma comes first in the copy search and wins the tie between the identical sources. + for name in ("a/Small0.java", "a/Small1.java", *(f"c/Small{index}.java" for index in range(2, 10))): + git.write(name, fixture("apache") + "x\n") + git.write("b/Alpha.java", fixture("apache") + self.BODY) + git.write("e/Gamma.java", fixture("apache") + self.BODY) + git.commit("CE") + git.write("d/Delta.java", fixture(p.NON_CE) + self.BODY) + self.relicensing = git.commit("relicensing") + self.scope = ["d/Delta.java"] + self.output = self.repo / "target/report.json" + + def test_size_filter_keeps_the_copy_search_result(self): + _, filtered, output = self.check() + with (patch.object(p, "could_shrink_to_copy", return_value=True), + patch.object(p, "could_be_copy", return_value=True)): + _, unfiltered, unfiltered_output = self.check() + self.assertEqual(unfiltered, filtered) + row = self.rows(filtered)["d/Delta.java"] + self.assertEqual(("unresolved", "apache"), (row["status"], row["suggestedHeader"])) + self.assertEqual(["e/Gamma.java"], [copy["path"] for copy in row["copyCandidates"]]) + self.assertIn("2 of 12 other CE files searched for copies", output) + self.assertIn("12 of 12 other CE files searched for copies", unfiltered_output) + + def test_a_file_grown_by_normalizing_fails_the_check(self): + def strip_headers(tool): + tool.removed, tool.stacked = {key: b"" for key in tool.contents}, set() + for key, content in list(tool.contents.items()): + tool.write(key, content + b"appended by a broken normalizer\n") + return {key: p.comparison_hash(content) for key, content in tool.contents.items()} + + code, _, output = self.check(normalizer=strip_headers) + self.assertEqual(2, code) + self.assertIn("Mycila grew these files while removing their headers", output) + + +class CacheTests(unittest.TestCase): + LINES = CheckCommandTests.LINES + setUp = CheckCommandTests.setUp + check = CheckCommandTests.check + + def normalizer(self, seen): + def strip_headers(tool): + seen.append(sorted(tool.contents)) + tool.removed, tool.stacked = {}, set() + for key, body in list(tool.contents.items()): + first, _, rest = body.partition(b"\n") + header = first.startswith(b"// ") + tool.removed[key] = first + b"\n" if header else b"" + tool.write(key, rest if header else body) + return {key: p.comparison_hash(body) for key, body in tool.contents.items()} + return strip_headers + + def cache(self): + return self.repo / p.CACHE_DIRECTORY + + def test_a_second_run_takes_ce_inputs_from_the_cache_and_reports_the_same(self): + first, second = [], [] + _, cold, _ = self.check(normalizer=self.normalizer(first)) + self.assertTrue((self.cache() / p.CACHE_UPDATED).exists()) + _, warm, output = self.check(normalizer=self.normalizer(second)) + self.assertEqual(cold, warm) + self.assertTrue(any(key[0] != "head" for batch in first for key in batch)) + self.assertEqual({"head"}, {key[0] for batch in second for key in batch}) + self.assertFalse((self.cache() / p.CACHE_UPDATED).exists()) + self.assertRegex(output, r"[1-9][0-9]* from the cache") + + def test_without_the_cache_nothing_is_read_or_written(self): + self.check() + seen = [] + _, report, output = self.check("--no-cache", normalizer=self.normalizer(seen)) + self.assertTrue(any(key[0] != "head" for batch in seen for key in batch)) + self.assertIn(" 0 from the cache", output) + shutil_tree = sorted(path.name for path in self.cache().iterdir()) + self.check("--no-cache") + self.assertEqual(shutil_tree, sorted(path.name for path in self.cache().iterdir())) + + def test_entries_are_keyed_by_content_and_file_name(self): + cache = p.NormalizationCache(temporary_directory(self), "signature") + cache.put([(("A.java", "a"), b"// header\nbody\n", b"body\n")]) + self.assertEqual({("moved/A.java", "b"): b"body\n"}, cache.get({("moved/A.java", "b"): b"// header\nbody\n"})) + self.assertEqual({}, cache.get({("B.java", "b"): b"// header\nbody\n"})) + self.assertEqual({}, cache.get({("A.xml", "a"): b"// header\nbody\n"})) + self.assertEqual({}, cache.get({("A.java", "a"): b"// header\nother\n"})) + cache.close() + + def test_signature_follows_everything_that_shapes_normalization(self): + repo = temporary_directory(self) + for header, name in p.TEMPLATES.items(): + (repo / name).parent.mkdir(parents=True, exist_ok=True) + (repo / name).write_text(f"fixture {header}\n") + signature = p.cache_signature(repo, fixture_plugin("1")) + self.assertEqual(signature, p.cache_signature(repo, fixture_plugin("1"))) + self.assertNotEqual(signature, p.cache_signature(repo, fixture_plugin("2"))) + other = p.Plugin("1", ET.fromstring("SLASHSTAR_STYLE")) + self.assertNotEqual(signature, p.cache_signature(repo, other)) + with patch.object(p, "CACHE_FORMAT", "other"): + self.assertNotEqual(signature, p.cache_signature(repo, fixture_plugin("1"))) + (repo / p.TEMPLATES["apache"]).write_text("reworded\n") + self.assertNotEqual(signature, p.cache_signature(repo, fixture_plugin("1"))) + + def test_only_recent_signatures_are_kept_and_the_update_mark_is_fresh(self): + directory = temporary_directory(self) + for index in range(p.CACHE_SIGNATURES_KEPT + 2): + stale = directory / f"old{index}.sqlite" + stale.write_bytes(b"") + os.utime(stale, (index, index)) + (directory / p.CACHE_UPDATED).touch() + cache = p.NormalizationCache(directory, "current") + self.assertFalse((directory / p.CACHE_UPDATED).exists()) + kept = sorted(path.name for path in directory.glob("*.sqlite")) + self.assertEqual(p.CACHE_SIGNATURES_KEPT, len(kept)) + self.assertIn("current.sqlite", kept) + cache.close() + self.assertFalse((directory / p.CACHE_UPDATED).exists()) + + def test_a_damaged_cache_is_started_again(self): + directory = temporary_directory(self) + (directory / "damaged.sqlite").write_bytes(b"not a database, cut off by a failed restore") + cache = p.NormalizationCache(directory, "damaged") + self.assertEqual({}, cache.get({("A.java", "a"): b"raw"})) + cache.put([(("A.java", "a"), b"raw", b"normalized")]) + cache.close() + self.assertEqual({("A.java", "a"): b"normalized"}, + p.NormalizationCache(directory, "damaged").get({("A.java", "a"): b"raw"})) + + def test_the_cache_of_a_branch_checked_long_ago_survives_newer_signatures(self): + directory = temporary_directory(self) + p.NormalizationCache(directory, "revisited").close() + os.utime(directory / "revisited.sqlite", (1, 1)) + for index in range(p.CACHE_SIGNATURES_KEPT): + (directory / f"newer{index}.sqlite").write_bytes(b"") + cache = p.NormalizationCache(directory, "revisited") + cache.put([(("A.java", "a"), b"raw", b"normalized")]) + cache.close() + self.assertTrue((directory / "revisited.sqlite").exists()) + + @unittest.skipUnless(os.environ.get("LICENSE_HEADERS_MAVEN_TESTS") == "1", "opt-in Maven fixtures") class MavenTests(unittest.TestCase): def test_scope_reports_respect_module_relative_exclusions(self): - repo = temporary_directory(self) + repo = temporary_directory(self).resolve() # macOS: /var/folders is a symlink to /private/var/folders p.git(repo, "init") (repo / "header.txt").write_text("SPDX-FileCopyrightText: Copyright Example\n" "SPDX-License-Identifier: Apache-2.0\n") From ce671c9efc7b31ec2762d1598ff6cb551c0bc38b Mon Sep 17 00:00:00 2001 From: Vladyslav_Prykhodko Date: Thu, 12 Nov 2026 10:51:31 +0200 Subject: [PATCH 05/21] Recovered a license header cache damaged below its schema; pull requests restore the base branch cache by name --- .github/workflows/check-license-headers.yml | 2 +- .../license-headers/check_license_headers.py | 4 ++++ .../test_check_license_headers.py | 18 ++++++++++++++++++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/.github/workflows/check-license-headers.yml b/.github/workflows/check-license-headers.yml index d8cebb1815..66d7b295f2 100644 --- a/.github/workflows/check-license-headers.yml +++ b/.github/workflows/check-license-headers.yml @@ -54,7 +54,7 @@ jobs: path: target/license-headers-cache key: license-headers-ce-v1-${{ github.ref_name }}-${{ github.run_id }} restore-keys: | - license-headers-ce-v1-${{ github.ref_name }}- + license-headers-ce-v1-${{ github.base_ref || github.ref_name }}- license-headers-ce-v1- - name: Check license headers diff --git a/tools/src/main/python/license-headers/check_license_headers.py b/tools/src/main/python/license-headers/check_license_headers.py index ec520d9fb9..ec024f470d 100644 --- a/tools/src/main/python/license-headers/check_license_headers.py +++ b/tools/src/main/python/license-headers/check_license_headers.py @@ -936,6 +936,10 @@ class NormalizationCache: def open(self): database = sqlite3.connect(self.path, check_same_thread=False) database.execute("CREATE TABLE IF NOT EXISTS normalized (input TEXT PRIMARY KEY, content BLOB NOT NULL)") + # Opening reads only the schema: a file damaged below it would fail on the first lookup instead. + if database.execute("PRAGMA quick_check").fetchone()[0] != "ok": + database.close() + raise sqlite3.DatabaseError(f"{self.path} is damaged") return database @staticmethod diff --git a/tools/src/main/python/license-headers/test_check_license_headers.py b/tools/src/main/python/license-headers/test_check_license_headers.py index 0756cc41bd..7eb94b401c 100644 --- a/tools/src/main/python/license-headers/test_check_license_headers.py +++ b/tools/src/main/python/license-headers/test_check_license_headers.py @@ -1304,6 +1304,24 @@ class CacheTests(unittest.TestCase): self.assertEqual({("A.java", "a"): b"normalized"}, p.NormalizationCache(directory, "damaged").get({("A.java", "a"): b"raw"})) + def test_a_cache_damaged_after_its_schema_is_started_again(self): + directory = temporary_directory(self) + cache = p.NormalizationCache(directory, "damaged") + cache.put([((f"F{index}.java", "a"), f"raw {index}".encode(), b"normalized" * 400) for index in range(300)]) + cache.close() + database = directory / "damaged.sqlite" + page = 4096 + with database.open("r+b") as file: + # The schema and the root pages stay readable, so the file opens; every lookup below them fails. + file.seek(4 * page) + file.write(b"\xff" * (database.stat().st_size - 4 * page)) + cache = p.NormalizationCache(directory, "damaged") + self.assertEqual({}, cache.get({("F0.java", "a"): b"raw 0"})) + cache.put([(("A.java", "a"), b"raw", b"normalized")]) + cache.close() + self.assertEqual({("A.java", "a"): b"normalized"}, + p.NormalizationCache(directory, "damaged").get({("A.java", "a"): b"raw"})) + def test_the_cache_of_a_branch_checked_long_ago_survives_newer_signatures(self): directory = temporary_directory(self) p.NormalizationCache(directory, "revisited").close() From 2e2ac366c3d886a2430365e4f3b6474f5bbf77fd Mon Sep 17 00:00:00 2001 From: Vladyslav_Prykhodko Date: Thu, 12 Nov 2026 11:27:57 +0200 Subject: [PATCH 06/21] Copy search under --since takes CE sources of every type a full run takes; a restored cache marker no longer re-saves the cache --- .github/workflows/check-license-headers.yml | 2 + .../src/main/python/license-headers/README.md | 4 +- .../license-headers/check_license_headers.py | 10 +++-- .../test_check_license_headers.py | 44 +++++++++++++++++++ 4 files changed, 56 insertions(+), 4 deletions(-) diff --git a/.github/workflows/check-license-headers.yml b/.github/workflows/check-license-headers.yml index 66d7b295f2..54da6cea99 100644 --- a/.github/workflows/check-license-headers.yml +++ b/.github/workflows/check-license-headers.yml @@ -63,6 +63,8 @@ jobs: SINCE: ${{ github.event_name == 'pull_request' && format('origin/{0}', github.base_ref) || '' }} run: | mkdir -p target/license-provenance + # A restored cache carries the marker of the run that saved it; only this run's additions may set it. + rm -f target/license-headers-cache/.updated # The runner does nothing else: use every CPU, not all but one as on a workstation. LICENSE_HEADERS_JOBS="$(nproc)" export LICENSE_HEADERS_JOBS diff --git a/tools/src/main/python/license-headers/README.md b/tools/src/main/python/license-headers/README.md index 0c6fb3300f..9f854b548a 100644 --- a/tools/src/main/python/license-headers/README.md +++ b/tools/src/main/python/license-headers/README.md @@ -67,7 +67,9 @@ are still reported for the whole repository. The check falls back to every file when a change can move the verdict of an unchanged file: new CE commits merged into the branch, a changed Mycila -configuration in the root `pom.xml`, or a change to the check itself. +configuration in the root `pom.xml`, or a change to the check itself. Other +changes to the Mycila scope, such as a module added to ``, do not +trigger it: the files they bring into scope are checked by the next push. ## Fix automatically diff --git a/tools/src/main/python/license-headers/check_license_headers.py b/tools/src/main/python/license-headers/check_license_headers.py index ec024f470d..8839a59f8d 100644 --- a/tools/src/main/python/license-headers/check_license_headers.py +++ b/tools/src/main/python/license-headers/check_license_headers.py @@ -1024,15 +1024,19 @@ def could_shrink_to_copy(raw_size, destinations): return 2 * raw_size >= min(destinations) -def compare(repo, plugin, lineage, contents, cache): +def compare(repo, plugin, lineage, contents, cache, in_scope): names = list(contents) new_paths = {name for name in names if not lineage.versions(name)} + # Copy sources follow every path in scope that CE lacks, not only the checked ones: with --since they would + # otherwise depend on the files a pull request changes and miss copies that a full run finds. Without new paths + # nothing is searched for copies, so no CE file needs to be read for it. + copy_source_types = {name for name in in_scope if not lineage.versions(name)} if new_paths else set() sources = {} for base, files in lineage.trees.items(): for name in names: if name in files: sources.setdefault((name, files[name]), base) - for key in comparable_ce_files(files, new_paths).items(): + for key in comparable_ce_files(files, copy_source_types).items(): sources.setdefault(key, base) versions = {(name, oid) for name in names for _, oid in lineage.versions(name)} # Every input keeps the slot it has among all inputs, so the copy search sees the same paths, and Git breaks @@ -1468,7 +1472,7 @@ def check(args): cache = (NoCache() if args.no_cache else NormalizationCache((repo / args.cache).resolve(), cache_signature(repo, plugin))) try: - comparison = compare(repo, plugin, lineage, contents, cache) + comparison = compare(repo, plugin, lineage, contents, cache, scope.eligible) finally: cache.close() rows = [comparison.classify(name, curations.get(name)) for name in checked] diff --git a/tools/src/main/python/license-headers/test_check_license_headers.py b/tools/src/main/python/license-headers/test_check_license_headers.py index 7eb94b401c..72e21499be 100644 --- a/tools/src/main/python/license-headers/test_check_license_headers.py +++ b/tools/src/main/python/license-headers/test_check_license_headers.py @@ -985,6 +985,50 @@ class CheckCommandTests(unittest.TestCase): self.assertEqual(["New.java"], self.checked(report)) self.assertEqual([], report["curationIssues"]) + def test_since_finds_a_copy_of_a_ce_file_with_another_extension_as_a_full_run_does(self): + # CE sources of the copy search follow the extensions of every path CE lacks: New.java brings .java in. + self.pull_request() + self.git.write("Copy.kt", fixture(p.NON_CE) + self.body) + self.git.commit("copy a CE file into another language") + scope = self.scope + ["Copy.kt"] + _, full, _ = self.check(scope=scope) + code, since, _ = self.check("--since", "master", scope=scope) + self.assertEqual(1, code) + self.assertEqual(["Copy.kt"], self.checked(since)) + row = self.rows(since)["Copy.kt"] + self.assertEqual(self.rows(full)["Copy.kt"], row) + self.assertEqual(("unresolved", ["Source.java"]), + (row["status"], [copy["path"] for copy in row["copyCandidates"]])) + + def test_since_checks_every_file_when_the_merge_base_has_no_ce_bases(self): + self.pull_request() + _, report, output = self.check("--since", "lts-4.3") + self.assertEqual(sorted(self.scope), self.checked(report)) + self.assertEqual("the CE commits merged at the merge base cannot be resolved", report["selection"]["reason"]) + + def test_since_checks_every_curated_file_when_the_target_curations_cannot_be_read(self): + self.git.write(p.CURATIONS, "not JSON") + self.git.commit("damage curations.json") + self.pull_request() + curation = dict(path="Source.java", header="apache", reason="Reviewed", + contentHash=p.raw_hash((self.repo / "Source.java").read_bytes())) + self.git.write(p.CURATIONS, json.dumps(dict(schemaVersion=1, curations=[curation]))) + self.git.commit("repair curations.json") + code, report, _ = self.check("--since", "master") + self.assertEqual(0, code) + self.assertEqual(["Source.java"], self.checked(report)) + self.assertEqual(["Source.java"], report["redundantCurations"]) + + def test_since_does_not_check_every_file_when_only_the_readme_or_curations_of_the_check_change(self): + self.pull_request() + self.git.write(p.README, "notes\n") + self.git.write(p.CURATIONS, '{"schemaVersion": 1, "curations": [] }') + self.git.commit("document the check") + code, report, _ = self.check("--since", "master") + self.assertEqual((0, []), (code, report["files"])) + self.assertEqual({"since": "master", "mergeBase": self.git("rev-parse", "master"), "full": False, + "reason": "2 changed paths"}, report["selection"]) + def test_since_needs_shared_history(self): self.git("checkout", "-q", "--orphan", "unrelated") self.git.write("Other.java", "other\n") From 0390da86beb2154e5e67c759dd0904bd13164336 Mon Sep 17 00:00:00 2001 From: Roman Kostenko Date: Thu, 12 Nov 2026 15:54:06 +0200 Subject: [PATCH 07/21] Run SystemPatchApplier after application startup Migrations started from @PostConstruct ran before Spring registered @TransactionalEventListener methods, so cache evict events published by migrations were dropped. With a Redis cache the stale entry survived until its TTL (e.g. the internal Trendz API key kept its pre-migration permissions for up to 24 hours). Start the patch applier on ApplicationReadyEvent with the new AfterStartUp.SYSTEM_PATCH order (0), so it is still submitted before partitions, discovery, core and actor startup. --- .../server/service/system/SystemPatchApplier.java | 6 +++--- .../org/thingsboard/server/queue/util/AfterStartUp.java | 1 + 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/system/SystemPatchApplier.java b/application/src/main/java/org/thingsboard/server/service/system/SystemPatchApplier.java index bafaee6a3f..1ac83a6b33 100644 --- a/application/src/main/java/org/thingsboard/server/service/system/SystemPatchApplier.java +++ b/application/src/main/java/org/thingsboard/server/service/system/SystemPatchApplier.java @@ -7,7 +7,6 @@ import com.fasterxml.jackson.databind.JsonNode; import com.google.common.base.Charsets; import com.google.common.hash.Hashing; import com.google.common.io.Resources; -import jakarta.annotation.PostConstruct; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.jdbc.core.JdbcTemplate; @@ -20,6 +19,7 @@ import org.thingsboard.server.common.data.widget.WidgetsBundle; import org.thingsboard.server.dao.resource.ImageService; import org.thingsboard.server.dao.widget.WidgetTypeService; import org.thingsboard.server.dao.widget.WidgetsBundleService; +import org.thingsboard.server.queue.util.AfterStartUp; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.install.DatabaseSchemaSettingsService; import org.thingsboard.server.service.install.InstallScripts; @@ -66,8 +66,8 @@ public class SystemPatchApplier { private final ImageService imageService; private final MigrationService migrationService; - @PostConstruct - private void init() { + @AfterStartUp(order = AfterStartUp.SYSTEM_PATCH) + public void init() { ExecutorService executor = Executors.newSingleThreadExecutor(ThingsBoardThreadFactory.forName("system-patch-applier")); executor.submit(() -> { try { diff --git a/common/queue/src/main/java/org/thingsboard/server/queue/util/AfterStartUp.java b/common/queue/src/main/java/org/thingsboard/server/queue/util/AfterStartUp.java index bac154b879..28b5e180d4 100644 --- a/common/queue/src/main/java/org/thingsboard/server/queue/util/AfterStartUp.java +++ b/common/queue/src/main/java/org/thingsboard/server/queue/util/AfterStartUp.java @@ -18,6 +18,7 @@ import java.lang.annotation.Target; @Order public @interface AfterStartUp { + int SYSTEM_PATCH = 0; int QUEUE_INFO_INITIALIZATION = 1; int DISCOVERY_SERVICE = 2; From 1dd1d7c8f9a0cbf2db0888efb16aabc78f22912d Mon Sep 17 00:00:00 2001 From: Sergey Matvienko Date: Fri, 6 Nov 2026 11:48:53 +0100 Subject: [PATCH 08/21] Stop alarm and entity subscriptions from outliving their websocket session A subscription command can register subscriptions after its context was stopped by a concurrent session cleanup, or create a context after the session was already removed. The registrations then outlive the session and keep answering alarm updates with queries whose results are dropped. - Serialize TbAbstractSubCtx.stop() with subscription registration through a lifecycle lock; registerSubscription() refuses stopped contexts and sessions unknown to the websocket service. - Route all context-owned addSubscription calls through registerSubscription(). - Skip alarm fetches on stopped contexts and ignore alarm and entity data commands for sessions that are no longer registered. - Add WebSocketService.hasSession(). - Unit tests for the registration guard and the stop/registration ordering. --- ...efaultTbEntityDataSubscriptionService.java | 12 ++ .../subscription/TbAbstractDataSubCtx.java | 5 +- .../TbAbstractEntityQuerySubCtx.java | 13 +- .../subscription/TbAbstractSubCtx.java | 33 ++++- .../subscription/TbAlarmCountSubCtx.java | 2 +- .../subscription/TbAlarmDataSubCtx.java | 7 +- .../subscription/TbAlarmStatusSubCtx.java | 11 +- .../subscription/TbEntityDataSubCtx.java | 2 +- .../service/ws/DefaultWebSocketService.java | 5 + .../server/service/ws/WebSocketService.java | 2 + .../subscription/TbAbstractSubCtxTest.java | 115 ++++++++++++++++++ 11 files changed, 192 insertions(+), 15 deletions(-) create mode 100644 application/src/test/java/org/thingsboard/server/service/subscription/TbAbstractSubCtxTest.java diff --git a/application/src/main/java/org/thingsboard/server/service/subscription/DefaultTbEntityDataSubscriptionService.java b/application/src/main/java/org/thingsboard/server/service/subscription/DefaultTbEntityDataSubscriptionService.java index 800de01b2c..1407b4745f 100644 --- a/application/src/main/java/org/thingsboard/server/service/subscription/DefaultTbEntityDataSubscriptionService.java +++ b/application/src/main/java/org/thingsboard/server/service/subscription/DefaultTbEntityDataSubscriptionService.java @@ -162,6 +162,10 @@ public class DefaultTbEntityDataSubscriptionService implements TbEntityDataSubsc @Override public void handleCmd(WebSocketSessionRef session, EntityDataCmd cmd) { + if (!wsService.hasSession(session.getSessionId())) { + log.debug("[{}][{}] Ignoring entity data command for closed session", session.getSessionId(), cmd.getCmdId()); + return; + } TbEntityDataSubCtx ctx = getSubCtx(session.getSessionId(), cmd.getCmdId()); if (ctx != null) { log.debug("[{}][{}] Updating existing subscriptions using: {}", session.getSessionId(), cmd.getCmdId(), cmd); @@ -394,6 +398,10 @@ public class DefaultTbEntityDataSubscriptionService implements TbEntityDataSubsc @Override public void handleCmd(WebSocketSessionRef session, AlarmDataCmd cmd) { + if (!wsService.hasSession(session.getSessionId())) { + log.debug("[{}][{}] Ignoring alarm data command for closed session", session.getSessionId(), cmd.getCmdId()); + return; + } TbAlarmDataSubCtx ctx = getSubCtx(session.getSessionId(), cmd.getCmdId()); if (ctx == null) { log.debug("[{}][{}] Creating new alarm subscription using: {}", session.getSessionId(), cmd.getCmdId(), cmd); @@ -406,6 +414,10 @@ public class DefaultTbEntityDataSubscriptionService implements TbEntityDataSubsc long end = System.currentTimeMillis(); stats.getRegularQueryInvocationCnt().incrementAndGet(); stats.getRegularQueryTimeSpent().addAndGet(end - start); + if (ctx.isStopped()) { + log.debug("[{}][{}] Alarm data context was stopped while fetching data, skipping subscriptions", session.getSessionId(), cmd.getCmdId()); + return; + } List entities = ctx.getEntitiesData(); ctx.cancelTasks(); ctx.clearEntitySubscriptions(); diff --git a/application/src/main/java/org/thingsboard/server/service/subscription/TbAbstractDataSubCtx.java b/application/src/main/java/org/thingsboard/server/service/subscription/TbAbstractDataSubCtx.java index 8032342767..8df17fdb4a 100644 --- a/application/src/main/java/org/thingsboard/server/service/subscription/TbAbstractDataSubCtx.java +++ b/application/src/main/java/org/thingsboard/server/service/subscription/TbAbstractDataSubCtx.java @@ -118,8 +118,7 @@ public abstract class TbAbstractDataSubCtx { int subIdx = sessionRef.getSessionSubIdSeq().incrementAndGet(); subToEntityIdMap.put(subIdx, entityData.getEntityId()); - localSubscriptionService.addSubscription( - createTsSub(entityData, subIdx, false, startTs, endTs, keyStates, resultToLatestValues), sessionRef); + registerSubscription(createTsSub(entityData, subIdx, false, startTs, endTs, keyStates, resultToLatestValues)); }); } @@ -127,7 +126,7 @@ public abstract class TbAbstractDataSubCtx> keysByType = getEntityKeyByTypeMap(keys); for (EntityData entityData : data.getData()) { List entitySubscriptions = addSubscriptions(entityData, keysByType, latestValues, startTs, endTs); - entitySubscriptions.forEach(subscription -> localSubscriptionService.addSubscription(subscription, sessionRef)); + entitySubscriptions.forEach(this::registerSubscription); } } diff --git a/application/src/main/java/org/thingsboard/server/service/subscription/TbAbstractEntityQuerySubCtx.java b/application/src/main/java/org/thingsboard/server/service/subscription/TbAbstractEntityQuerySubCtx.java index 03e5ed92d0..be14bba1bb 100644 --- a/application/src/main/java/org/thingsboard/server/service/subscription/TbAbstractEntityQuerySubCtx.java +++ b/application/src/main/java/org/thingsboard/server/service/subscription/TbAbstractEntityQuerySubCtx.java @@ -74,9 +74,14 @@ public abstract class TbAbstractEntityQuerySubCtx ex } public void stop() { - super.stop(); - cancelTasks(); - clearSubscriptions(); + lifecycleLock.lock(); + try { + super.stop(); + cancelTasks(); + clearSubscriptions(); + } finally { + lifecycleLock.unlock(); + } } public void setAndResolveQuery(T query) { @@ -137,7 +142,7 @@ public abstract class TbAbstractEntityQuerySubCtx ex .scope(TbAttributeSubscriptionScope.SERVER_SCOPE) .build(); subToDynamicValueKeySet.add(subIdx); - localSubscriptionService.addSubscription(sub, sessionRef); + registerSubscription(sub); } } catch (InterruptedException | ExecutionException e) { log.info("[{}][{}][{}] Failed to resolve dynamic values: {}", tenantId, customerId, userId, dynamicValues.keySet()); diff --git a/application/src/main/java/org/thingsboard/server/service/subscription/TbAbstractSubCtx.java b/application/src/main/java/org/thingsboard/server/service/subscription/TbAbstractSubCtx.java index 25bd438f3a..fd36cac030 100644 --- a/application/src/main/java/org/thingsboard/server/service/subscription/TbAbstractSubCtx.java +++ b/application/src/main/java/org/thingsboard/server/service/subscription/TbAbstractSubCtx.java @@ -49,6 +49,11 @@ public abstract class TbAbstractSubCtx { @Getter protected final Lock wsLock = new ReentrantLock(true); + /** + * Serializes context stop with subscription registration, so a subscription is either registered before + * {@link #stop()} (and cancelled by it) or never registered. + */ + protected final ReentrantLock lifecycleLock = new ReentrantLock(); protected final String serviceId; protected final SubscriptionServiceStatistics stats; private final WebSocketService wsService; @@ -75,7 +80,33 @@ public abstract class TbAbstractSubCtx { public abstract boolean isDynamic(); public void stop() { - stopped = true; + lifecycleLock.lock(); + try { + stopped = true; + } finally { + lifecycleLock.unlock(); + } + } + + /** + * Registers a subscription owned by this context. Refused when the context is stopped or when its websocket + * session is no longer registered, so that a subscription cannot outlive the session that created it. + */ + protected void registerSubscription(TbSubscription subscription) { + lifecycleLock.lock(); + try { + if (stopped) { + log.debug("[{}][{}] Skipping subscription registration for stopped context: {}", getSessionId(), cmdId, subscription); + return; + } + if (!wsService.hasSession(getSessionId())) { + log.debug("[{}][{}] Skipping subscription registration for closed session: {}", getSessionId(), cmdId, subscription); + return; + } + localSubscriptionService.addSubscription(subscription, sessionRef); + } finally { + lifecycleLock.unlock(); + } } public String getSessionId() { diff --git a/application/src/main/java/org/thingsboard/server/service/subscription/TbAlarmCountSubCtx.java b/application/src/main/java/org/thingsboard/server/service/subscription/TbAlarmCountSubCtx.java index 59067d266c..4ea43af3ad 100644 --- a/application/src/main/java/org/thingsboard/server/service/subscription/TbAlarmCountSubCtx.java +++ b/application/src/main/java/org/thingsboard/server/service/subscription/TbAlarmCountSubCtx.java @@ -142,7 +142,7 @@ public class TbAlarmCountSubCtx extends TbAbstractEntityQuerySubCtx fetchAlarmCount()) .build(); - localSubscriptionService.addSubscription(subscription, sessionRef); + registerSubscription(subscription); } public void clearAlarmSubscriptions() { diff --git a/application/src/main/java/org/thingsboard/server/service/subscription/TbAlarmDataSubCtx.java b/application/src/main/java/org/thingsboard/server/service/subscription/TbAlarmDataSubCtx.java index 8587c5758c..fcc5d19c5d 100644 --- a/application/src/main/java/org/thingsboard/server/service/subscription/TbAlarmDataSubCtx.java +++ b/application/src/main/java/org/thingsboard/server/service/subscription/TbAlarmDataSubCtx.java @@ -86,6 +86,9 @@ public class TbAlarmDataSubCtx extends TbAbstractDataSubCtx { } public void fetchAlarms() { + if (stopped) { + return; + } alarmInvocationAttempts++; log.trace("[{}] Fetching alarms: {}", cmdId, alarmInvocationAttempts); if (alarmInvocationAttempts <= maxAlarmQueriesPerRefreshInterval) { @@ -169,7 +172,7 @@ public class TbAlarmDataSubCtx extends TbAbstractDataSubCtx { .updateProcessor((sub, update) -> sendWsMsg(sub.getSessionId(), update)) .ts(startTs) .build(); - localSubscriptionService.addSubscription(subscription, sessionRef); + registerSubscription(subscription); } @Override @@ -333,7 +336,7 @@ public class TbAlarmDataSubCtx extends TbAbstractDataSubCtx { newSubsList.forEach(entity -> createAlarmSubscriptionForEntity(query.getPageLink(), startTs, entity)); } subIdsToCancel.forEach(subId -> localSubscriptionService.cancelSubscription(getTenantId(), getSessionId(), subId)); - subsToAdd.forEach(subscription -> localSubscriptionService.addSubscription(subscription, sessionRef)); + subsToAdd.forEach(this::registerSubscription); } private void resetInvocationCounter() { diff --git a/application/src/main/java/org/thingsboard/server/service/subscription/TbAlarmStatusSubCtx.java b/application/src/main/java/org/thingsboard/server/service/subscription/TbAlarmStatusSubCtx.java index 46b0a9fc31..4e537d8d49 100644 --- a/application/src/main/java/org/thingsboard/server/service/subscription/TbAlarmStatusSubCtx.java +++ b/application/src/main/java/org/thingsboard/server/service/subscription/TbAlarmStatusSubCtx.java @@ -44,8 +44,13 @@ public class TbAlarmStatusSubCtx extends TbAbstractSubCtx { @Override public void stop() { - super.stop(); - localSubscriptionService.cancelSubscription(getTenantId(), sessionRef.getSessionId(), subscription.getSubscriptionId()); + lifecycleLock.lock(); + try { + super.stop(); + localSubscriptionService.cancelSubscription(getTenantId(), sessionRef.getSessionId(), subscription.getSubscriptionId()); + } finally { + lifecycleLock.unlock(); + } } public void createSubscription(AlarmStatusCmd cmd) { @@ -60,7 +65,7 @@ public class TbAlarmStatusSubCtx extends TbAbstractSubCtx { .severityList(cmd.getSeverityList()) .updateProcessor(this::handleAlarmStatusSubscriptionUpdate) .build(); - localSubscriptionService.addSubscription(subscription, sessionRef); + registerSubscription(subscription); } public void sendUpdate() { diff --git a/application/src/main/java/org/thingsboard/server/service/subscription/TbEntityDataSubCtx.java b/application/src/main/java/org/thingsboard/server/service/subscription/TbEntityDataSubCtx.java index 2b159b0531..813d3475ce 100644 --- a/application/src/main/java/org/thingsboard/server/service/subscription/TbEntityDataSubCtx.java +++ b/application/src/main/java/org/thingsboard/server/service/subscription/TbEntityDataSubCtx.java @@ -208,7 +208,7 @@ public class TbEntityDataSubCtx extends TbAbstractDataSubCtx { } } subIdsToCancel.forEach(subId -> localSubscriptionService.cancelSubscription(getTenantId(), getSessionId(), subId)); - subsToAdd.forEach(subscription -> localSubscriptionService.addSubscription(subscription, sessionRef)); + subsToAdd.forEach(this::registerSubscription); sendWsMsg(new EntityDataUpdate(cmdId, data, null, maxEntitiesPerDataSubscription)); } diff --git a/application/src/main/java/org/thingsboard/server/service/ws/DefaultWebSocketService.java b/application/src/main/java/org/thingsboard/server/service/ws/DefaultWebSocketService.java index 15e470085b..29a1da7a8d 100644 --- a/application/src/main/java/org/thingsboard/server/service/ws/DefaultWebSocketService.java +++ b/application/src/main/java/org/thingsboard/server/service/ws/DefaultWebSocketService.java @@ -282,6 +282,11 @@ public class DefaultWebSocketService implements WebSocketService { } } + @Override + public boolean hasSession(String sessionId) { + return wsSessionsMap.containsKey(sessionId); + } + @Override public void close(String sessionId, CloseStatus status) { WsSessionMetaData md = wsSessionsMap.get(sessionId); diff --git a/application/src/main/java/org/thingsboard/server/service/ws/WebSocketService.java b/application/src/main/java/org/thingsboard/server/service/ws/WebSocketService.java index 27d85821f2..daebf015c3 100644 --- a/application/src/main/java/org/thingsboard/server/service/ws/WebSocketService.java +++ b/application/src/main/java/org/thingsboard/server/service/ws/WebSocketService.java @@ -27,4 +27,6 @@ public interface WebSocketService { void cleanupIfStale(TenantId tenantId, String sessionId); + boolean hasSession(String sessionId); + } diff --git a/application/src/test/java/org/thingsboard/server/service/subscription/TbAbstractSubCtxTest.java b/application/src/test/java/org/thingsboard/server/service/subscription/TbAbstractSubCtxTest.java new file mode 100644 index 0000000000..d0c7039b55 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/subscription/TbAbstractSubCtxTest.java @@ -0,0 +1,115 @@ +// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.subscription; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; +import org.thingsboard.server.service.ws.WebSocketService; +import org.thingsboard.server.service.ws.WebSocketSessionRef; + +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.willAnswer; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +public class TbAbstractSubCtxTest { + + private static final String SESSION_ID = "session-1"; + private static final int CMD_ID = 7; + + private final WebSocketService wsService = mock(WebSocketService.class); + private final TbLocalSubscriptionService localSubscriptionService = mock(TbLocalSubscriptionService.class); + private final WebSocketSessionRef sessionRef = mock(WebSocketSessionRef.class); + private final TbSubscription subscription = mock(TbSubscription.class); + + private TbAbstractSubCtx subCtx; + + @BeforeEach + public void setUp() { + lenient().when(sessionRef.getSessionId()).thenReturn(SESSION_ID); + subCtx = new TbAbstractSubCtx("service", wsService, localSubscriptionService, mock(SubscriptionServiceStatistics.class), + sessionRef, CMD_ID) { + @Override + public boolean isDynamic() { + return false; + } + }; + } + + @Test + public void registersSubscriptionWhenContextActiveAndSessionOpen() { + when(wsService.hasSession(SESSION_ID)).thenReturn(true); + + subCtx.registerSubscription(subscription); + + verify(localSubscriptionService).addSubscription(subscription, sessionRef); + } + + @Test + public void doesNotRegisterSubscriptionAfterStop() { + subCtx.stop(); + + subCtx.registerSubscription(subscription); + + verify(localSubscriptionService, never()).addSubscription(any(), any()); + } + + @Test + public void doesNotRegisterSubscriptionForSessionUnknownToWebSocketService() { + when(wsService.hasSession(SESSION_ID)).thenReturn(false); + + subCtx.registerSubscription(subscription); + + verify(localSubscriptionService, never()).addSubscription(any(), any()); + } + + @Test + public void stopWaitsForInFlightRegistration() throws Exception { + when(wsService.hasSession(SESSION_ID)).thenReturn(true); + CountDownLatch registrationEntered = new CountDownLatch(1); + CountDownLatch releaseRegistration = new CountDownLatch(1); + List events = new CopyOnWriteArrayList<>(); + willAnswer(invocation -> { + events.add("register"); + registrationEntered.countDown(); + releaseRegistration.await(10, TimeUnit.SECONDS); + return null; + }).given(localSubscriptionService).addSubscription(any(), any()); + + Thread registrar = new Thread(() -> subCtx.registerSubscription(subscription)); + registrar.start(); + assertThat(registrationEntered.await(10, TimeUnit.SECONDS)).isTrue(); + + Thread stopper = new Thread(() -> { + subCtx.stop(); + events.add("stop"); + }); + stopper.start(); + stopper.join(200); + assertThat(stopper.isAlive()).as("stop() must wait for the in-flight registration").isTrue(); + + releaseRegistration.countDown(); + registrar.join(10_000); + stopper.join(10_000); + + assertThat(events).containsExactly("register", "stop"); + assertThat(subCtx.isStopped()).isTrue(); + + subCtx.registerSubscription(subscription); + verify(localSubscriptionService, times(1)).addSubscription(any(), any()); + } + +} From a861e8b9dcfdc5167faaae35dcf6a164f9cc77ff Mon Sep 17 00:00:00 2001 From: dshvaika Date: Thu, 12 Nov 2026 18:08:19 +0200 Subject: [PATCH 09/21] IoT Hub device packages: the install state of a step is keyed by its type and name, and the update wizard shows what each step will do --- .../DefaultDevicePackageUpdateService.java | 25 ++- .../service/iot_hub/DeviceUpdateRequest.java | 10 +- .../service/iot_hub/DeviceUpdateResult.java | 4 +- ...DefaultDevicePackageUpdateServiceTest.java | 83 +++++++-- .../iot_hub/DefaultIotHubServiceTest.java | 32 ++++ .../device-install-dialog.component.html | 14 +- .../device-install-dialog.component.scss | 33 +++- .../device-install-dialog.component.ts | 176 ++++++++++++------ .../iot-hub/iot-hub-actions.service.ts | 4 +- .../iot-hub/iot-hub-default-converter.ts | 1 + .../models/iot-hub/device-package.models.ts | 2 +- .../iot-hub/iot-hub-installed-item.models.ts | 5 +- .../assets/locale/locale.constant-en_US.json | 10 +- 13 files changed, 291 insertions(+), 108 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java index 1becc88cf4..47d9e64804 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java @@ -177,8 +177,8 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i validateIntegrations(tenantId, request); applied = transactionTemplate.execute(status -> applySteps(tenantId, devicePackage, request, versionInfo)); } catch (StepFailure e) { - log.warn("[{}] Device package update of {} failed on step [{}], nothing was changed", tenantId, installedItemId, e.stepName, e.getCause()); - return DeviceUpdateResult.error(userMessage(e.getCause()), e.stepName); + log.warn("[{}] Device package update of {} failed on step [{}], nothing was changed", tenantId, installedItemId, e.stepKey, e.getCause()); + return DeviceUpdateResult.error(userMessage(e.getCause()), e.stepKey); } catch (RestClientException e) { log.error("[{}] IoT Hub request failed while updating device package {}", tenantId, installedItemId, e); return DeviceUpdateResult.error("IoT Hub is unavailable. Try again later.", null); @@ -214,9 +214,8 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i if (step.getName() == null || step.getAction() == null || !isKnownType(step.getType())) { throw new IllegalArgumentException("Invalid update step: " + step.getName()); } - // The key of the step's install state - if (!stateKeys.add(step.getId() != null ? step.getId() : step.getName())) { - throw new IllegalArgumentException("Duplicate update step: " + step.getName()); + if (!stateKeys.add(step.stateKey())) { + throw new IllegalArgumentException("Duplicate update step: " + step.stateKey()); } boolean deviceOrGateway = "DEVICE".equals(step.getType()) || "GATEWAY".equals(step.getType()); switch (step.getAction()) { @@ -267,9 +266,9 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i } catch (ExecutionException e) { // What the integration reports, e.g. wrong credentials, is what the user has to fix Throwable cause = e.getCause() != null ? e.getCause() : e; - throw new StepFailure(step.getName(), new IllegalArgumentException(cause.getMessage(), cause)); + throw new StepFailure(step.stateKey(), new IllegalArgumentException(cause.getMessage(), cause)); } catch (TimeoutException e) { - throw new StepFailure(step.getName(), new IllegalStateException("Timeout to validate the integration configuration")); + throw new StepFailure(step.stateKey(), new IllegalStateException("Timeout to validate the integration configuration")); } } } @@ -308,7 +307,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i StepResult result = applyStep(tenantId, step, entity); ObjectNode output = result.output(); aliasOutputs.put(STEP_ALIASES.get(step.getType()), output); - outputs.put(step.getName(), output); + outputs.put(step.stateKey(), output); ObjectNode state = JacksonUtil.newObjectNode(); state.set("entityOutput", output); // The package's own entity stays the package's, whatever the request says, so later versions update it @@ -328,7 +327,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i if (metadata != null) { state.set("metadata", metadata); } - installState.put(step.getId() != null ? step.getId() : step.getName(), state); + installState.put(step.stateKey(), state); // As at install, an entity used as it was is listed too, so a delete removes the metadata entries the // package added to it; usedExistingEntityIds keeps it the user's if (!stepEntityIds.contains(result.entityId())) { @@ -350,7 +349,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i } catch (StepFailure e) { throw e; } catch (Exception e) { - throw new StepFailure(step.getName(), e); + throw new StepFailure(step.stateKey(), e); } } @@ -989,11 +988,11 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i /** A step that failed: the transaction rolls back, and the wizard shows which step it was. */ private static class StepFailure extends RuntimeException { - private final String stepName; + private final String stepKey; - StepFailure(String stepName, Throwable cause) { + StepFailure(String stepKey, Throwable cause) { super(cause.getMessage(), cause); - this.stepName = stepName; + this.stepKey = stepKey; } } diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java index 13a9c2937e..223c2eb723 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java @@ -38,7 +38,7 @@ public class DeviceUpdateRequest { @Data public static class Step { private String name; - // The package step's id, which keys its install state; the name when not set + // The package step's stable id, so that a next version can rename the step private String id; // InstallStepType of the package: DEVICE_PROFILE, DEVICE, GATEWAY, GATEWAY_CONNECTOR, DASHBOARD, RULE_CHAIN, // UPLINK_CONVERTER, DOWNLINK_CONVERTER, INTEGRATION @@ -66,6 +66,14 @@ public class DeviceUpdateRequest { private JsonNode metadata; // UPLINK_CONVERTER: the step takes ThingsBoard's default converter, which the install state records for the update check private boolean defaultConverter; + + /** + * The key of the step's install state: its id, or else its type and name, so that two steps of an install + * method never share it. The install wizard keys the steps of an install the same way. + */ + public String stateKey() { + return id != null ? id : type + ":" + name; + } } } diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java index c229f42cff..5c8ec6e8d7 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java @@ -12,7 +12,7 @@ import java.util.Map; /** * Either everything was applied, or nothing was: on a failure the transaction was rolled back and failedStep - * names the step that failed, if one did. + * is the install state key of the step that failed, if one did. */ @Data @NoArgsConstructor @@ -23,7 +23,7 @@ public class DeviceUpdateResult { private String errorMessage; private String failedStep; private DeviceInstalledItemDescriptor descriptor; - // By step name: what the install instructions resolve, e.g. ${integration.httpEndpoint}, ${device.token} + // By install state key of the step: what the install instructions resolve, e.g. ${integration.httpEndpoint}, ${device.token} private Map outputs; public static DeviceUpdateResult success(DeviceInstalledItemDescriptor descriptor, Map outputs) { diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java index 9c30892737..2ebf946bae 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java @@ -206,7 +206,7 @@ class DefaultDevicePackageUpdateServiceTest { assertThat(installedItem.getItemVersionId()).isEqualTo(UUID.fromString(versionId)); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); // Of the saved dashboard, not read back by id: inside the transaction that may come from the cache - assertThat(descriptor.getInstallState().get("Dashboard").get("checksum").asText()) + assertThat(descriptor.getInstallState().get("DASHBOARD:Dashboard").get("checksum").asText()) .isEqualTo(EntityChecksum.of(savedDashboard.getValue())); assertThat(descriptor.getCreatedEntityIds()).contains(profileId, deviceId, dashboardId); } @@ -225,7 +225,7 @@ class DefaultDevicePackageUpdateServiceTest { assertThat(result.isSuccess()).isTrue(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); - assertThat(descriptor.getInstallState().get("Dashboard").get("checksum").asText()).isEqualTo("installed"); + assertThat(descriptor.getInstallState().get("DASHBOARD:Dashboard").get("checksum").asText()).isEqualTo("installed"); assertThat(descriptor.getSelectedInstallMethod()).isEqualTo("INTEGRATION_CHIRPSTACK"); verify(dashboardService, never()).saveDashboard(any(Dashboard.class)); } @@ -245,7 +245,7 @@ class DefaultDevicePackageUpdateServiceTest { assertThat(result.isSuccess()).isTrue(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); assertThat(descriptor.getInstallState().get("main-dashboard").get("checksum").asText()).isEqualTo("installed"); - assertThat(descriptor.getInstallState()).doesNotContainKeys("Dashboard", "Overview"); + assertThat(descriptor.getInstallState()).containsOnlyKeys("main-dashboard"); } @Test @@ -260,7 +260,7 @@ class DefaultDevicePackageUpdateServiceTest { assertThat(result.isSuccess()).isTrue(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); - assertThat(descriptor.getInstallState().get("Dashboard").has("checksum")).isFalse(); + assertThat(descriptor.getInstallState().get("DASHBOARD:Dashboard").has("checksum")).isFalse(); } @Test @@ -273,7 +273,7 @@ class DefaultDevicePackageUpdateServiceTest { assertThat(result.isSuccess()).isTrue(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); - assertThat(descriptor.getInstallState().get("Overview").get("resolution").asText()).isEqualTo("created"); + assertThat(descriptor.getInstallState().get("DASHBOARD:Overview").get("resolution").asText()).isEqualTo("created"); assertThat(descriptor.getCreatedEntityIds()).contains(dashboardId); } @@ -289,7 +289,7 @@ class DefaultDevicePackageUpdateServiceTest { assertThat(result.isSuccess()).isTrue(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); - assertThat(descriptor.getInstallState().get("Dashboard").get("resolution").asText()).isEqualTo("use-existing"); + assertThat(descriptor.getInstallState().get("DASHBOARD:Dashboard").get("resolution").asText()).isEqualTo("use-existing"); } @Test @@ -334,7 +334,7 @@ class DefaultDevicePackageUpdateServiceTest { assertThat(result.isSuccess()).isTrue(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); - assertThat(descriptor.getInstallState().get("Dashboard").get("resolution").asText()).isEqualTo("created"); + assertThat(descriptor.getInstallState().get("DASHBOARD:Dashboard").get("resolution").asText()).isEqualTo("created"); } @Test @@ -395,7 +395,7 @@ class DefaultDevicePackageUpdateServiceTest { // A copy is saved: the integration read, possibly the cache's own instance, stays as it is until the commit assertThat(saved.getValue()).isNotSameAs(current); assertThat(current.getConfiguration().get("metadata").has("profile.lansitec-badge")).isFalse(); - JsonNode state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState().get("TTN"); + JsonNode state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState().get("INTEGRATION:TTN"); assertThat(state.get("resolution").asText()).isEqualTo("use-existing"); // The entries the step added, which a delete of the package removes; not the one it removed assertThat(state.get("metadata")).isEqualTo(JacksonUtil.newObjectNode().put("profile.lansitec-badge", "Badge")); @@ -450,7 +450,7 @@ class DefaultDevicePackageUpdateServiceTest { // entries from it (DefaultIotHubServiceTest#deleteInstalledItem_devicePackage_removesItsMetadataEntriesFromTheIntegrationItTookAsItWas) assertThat(descriptor.getCreatedEntityIds()).containsOnlyOnce(tenantsIntegrationId); assertThat(descriptor.getUsedExistingEntityIds()).containsExactly(tenantsIntegrationId); - JsonNode state = descriptor.getInstallState().get("TTN"); + JsonNode state = descriptor.getInstallState().get("INTEGRATION:TTN"); assertThat(state.get("resolution").asText()).isEqualTo("use-existing"); assertThat(state.get("metadata")).isEqualTo(JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308")); } @@ -487,6 +487,61 @@ class DefaultDevicePackageUpdateServiceTest { verify(installedItemService, never()).save(any(), any()); } + @Test + void twoStepsOfOneTypeAndName_areRejected() { + DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + keep("Dashboard", "DASHBOARD", dashboardId), keep("Dashboard", "DASHBOARD", dashboardId))); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getErrorMessage()).isEqualTo("Duplicate update step: DASHBOARD:Dashboard"); + verify(transactionTemplate, never()).execute(any()); + } + + @Test + void stepsOfOneNameAndAnotherType_eachKeepTheirOwnState() { + // Installed when the state was keyed by name: the integration's state replaced the converter's + ConverterId converterId = new ConverterId(UUID.randomUUID()); + Converter converter = new Converter(converterId); + converter.setTenantId(tenantId); + converter.setName("TTN my-app"); + when(converterService.findConverterById(tenantId, converterId)).thenReturn(converter); + Integration integration = new Integration(integrationId); + integration.setTenantId(tenantId); + integration.setName("TTN my-app"); + ObjectNode configuration = JacksonUtil.newObjectNode(); + configuration.set("metadata", JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308")); + integration.setConfiguration(configuration); + when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(integration); + DeviceInstalledItemDescriptor installed = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); + installed.setCreatedEntityIds(List.of(profileId, deviceId, converterId, integrationId)); + ObjectNode legacy = stateOf(integrationId, "created").put("checksum", "installed"); + legacy.set("metadata", JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308")); + installed.setInstallState(Map.of("${integrationName}", legacy, "${profileName}", stateOf(profileId, "created"), + "Configuration", JacksonUtil.newObjectNode().set("formValues", JacksonUtil.newObjectNode().put("integrationName", "TTN my-app")))); + DeviceUpdateRequest.Step uplink = keep("${integrationName}", "UPLINK_CONVERTER", converterId); + uplink.setDefaultConverter(true); + DeviceUpdateRequest.Step ttn = keep("${integrationName}", "INTEGRATION", integrationId); + ttn.setMetadata(JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308")); + DeviceUpdateRequest request = request(uplink, ttn); + request.setInstallState(Map.of("Configuration", installed.getInstallState().get("Configuration"))); + + DeviceUpdateResult result = service.apply(user, installedItem.getId(), request); + + assertThat(result.isSuccess()).isTrue(); + Map state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState(); + // The state under the name is gone: each step's is under its own key now + assertThat(state).containsOnlyKeys("Configuration", "UPLINK_CONVERTER:${integrationName}", "INTEGRATION:${integrationName}"); + JsonNode converterState = state.get("UPLINK_CONVERTER:${integrationName}"); + assertThat(converterState.get("entityOutput").get("id").asText()).isEqualTo(converterId.getId().toString()); + assertThat(converterState.get("defaultConverter").asBoolean()).isTrue(); + JsonNode integrationState = state.get("INTEGRATION:${integrationName}"); + assertThat(integrationState.get("entityOutput").get("id").asText()).isEqualTo(integrationId.getId().toString()); + assertThat(integrationState.get("checksum").asText()).isEqualTo("installed"); + assertThat(integrationState.get("metadata")).isEqualTo(JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308")); + assertThat(result.getOutputs().get("UPLINK_CONVERTER:${integrationName}").get("id").asText()).isEqualTo(converterId.getId().toString()); + assertThat(result.getOutputs().get("INTEGRATION:${integrationName}").get("id").asText()).isEqualTo(integrationId.getId().toString()); + } + @Test void failedStep_rollsBackAndReportsTheStep() { when(deviceProfileService.findDeviceProfileById(tenantId, profileId)).thenReturn(profile(3L, "AM308")); @@ -499,7 +554,7 @@ class DefaultDevicePackageUpdateServiceTest { overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d")))); assertThat(result.isSuccess()).isFalse(); - assertThat(result.getFailedStep()).isEqualTo("Dashboard"); + assertThat(result.getFailedStep()).isEqualTo("DASHBOARD:Dashboard"); assertThat(result.getErrorMessage()).isEqualTo("Dashboards limit reached"); assertThat(rolledBack).hasSize(1); verify(installedItemService, never()).save(any(), any()); @@ -515,7 +570,7 @@ class DefaultDevicePackageUpdateServiceTest { overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d")))); assertThat(result.isSuccess()).isFalse(); - assertThat(result.getFailedStep()).isEqualTo("Dashboard"); + assertThat(result.getFailedStep()).isEqualTo("DASHBOARD:Dashboard"); assertThat(result.getErrorMessage()).contains("Check the update again"); verify(dashboardService, never()).saveDashboard(any(Dashboard.class)); } @@ -550,7 +605,7 @@ class DefaultDevicePackageUpdateServiceTest { // The devices keep sending to the same endpoint assertThat(saved.getValue().getRoutingKey()).isEqualTo("routing-key"); assertThat(saved.getValue().getName()).isEqualTo("TTN my-app"); - assertThat(result.getOutputs().get("TTN").get("routingKey").asText()).isEqualTo("routing-key"); + assertThat(result.getOutputs().get("INTEGRATION:TTN").get("routingKey").asText()).isEqualTo("routing-key"); } @Test @@ -579,7 +634,7 @@ class DefaultDevicePackageUpdateServiceTest { DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); assertThat(result.isSuccess()).isTrue(); - JsonNode state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState().get("Uplink"); + JsonNode state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState().get("UPLINK_CONVERTER:Uplink"); assertThat(state.get("defaultConverter").asBoolean()).isTrue(); // The other packages keep what they recorded: check() takes the checksum of any installed package assertThat(created.get("checksum").asText()).isEqualTo("before"); @@ -631,7 +686,7 @@ class DefaultDevicePackageUpdateServiceTest { DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("Dashboard", "DASHBOARD", dashboardId))); assertThat(result.isSuccess()).isTrue(); - assertThat(((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState()).containsOnlyKeys("Dashboard"); + assertThat(((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState()).containsOnlyKeys("DASHBOARD:Dashboard"); } @Test diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java index d63be65c5c..a81368450c 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java @@ -599,6 +599,38 @@ class DefaultIotHubServiceTest { verify(integrationService, never()).deleteIntegration(any(), any()); } + @Test + void deleteInstalledItem_devicePackageInstalledWithStateByName_deletesTheConverterWhoseStateWasReplaced() throws Exception { + mockTenant(); + IntegrationId integrationId = new IntegrationId(UUID.randomUUID()); + Converter converter = new Converter(new ConverterId(UUID.randomUUID())); + when(converterService.findConverterById(tenantId, converter.getId())).thenReturn(converter); + IotHubInstalledItem deleted = devicePackage(converter.getId(), integrationId); + // The converter and the integration steps shared the name: the integration's state replaced the converter's + ObjectNode state = JacksonUtil.newObjectNode().put("resolution", "use-existing"); + state.set("entityOutput", JacksonUtil.newObjectNode().put("id", integrationId.getId().toString())); + state.set("metadata", JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308")); + DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) deleted.getDescriptor(); + descriptor.setInstallState(Map.of("${integrationName}", state)); + descriptor.setUsedExistingEntityIds(List.of(integrationId)); + when(iotHubInstalledItemService.findById(tenantId, deleted.getId())).thenReturn(deleted); + when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any())) + .thenReturn(new PageData<>(List.of(deleted), 1, 1, false)); + when(integrationService.findIntegrationById(tenantId, integrationId)) + .thenReturn(integration(integrationId, Map.of("profile.milesight-iot-am308", "AM308", "profile.added-by-user", "Mine"))); + + service.deleteInstalledItem(user, deleted.getId()); + + // Found by createdEntityIds, not by the install state + verify(tbConverterService).delete(converter, user); + ArgumentCaptor saved = ArgumentCaptor.forClass(Integration.class); + verify(integrationService).saveIntegration(saved.capture()); + verify(integrationService, never()).deleteIntegration(any(), any()); + JsonNode metadata = saved.getValue().getConfiguration().get("metadata"); + assertThat(metadata.has("profile.milesight-iot-am308")).isFalse(); + assertThat(metadata.get("profile.added-by-user").asText()).isEqualTo("Mine"); + } + @Test void findKeptEntities_devicePackage_namesTheSharedEntitiesAndCountsTheOtherPackages() { DeviceId deviceId = new DeviceId(UUID.randomUUID()); diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html index 695df118b5..23578f5490 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html @@ -237,7 +237,7 @@ } @case ('success') { - check_circle + check_circle } @default {
{{ i + 1 }}
@@ -258,9 +258,6 @@ @if (plan.newDefaultConverter) { {{ 'iot-hub.device-update-new-default-converter' | translate }} } - @if (plan.existing) { - {{ 'iot-hub.device-update-existing-' + plan.resolution | translate }} - } @if (plan.shared) { {{ 'iot-hub.device-update-shared' | translate }} } @@ -277,14 +274,17 @@ {{ 'iot-hub.in-progress' | translate }} } @case ('success') { - {{ updateOutcomeOf(plan) | translate }} + {{ updateOutcomeOf(plan) | translate }} } @case ('skipped') { {{ 'iot-hub.device-update-skipped' | translate }} } @default { - @if (ws.reviewing && plan) { - {{ 'iot-hub.device-update-no-conflicts' | translate }} + + @if (ws.reviewing && plan?.existing && plan.confirmed) { + {{ 'iot-hub.device-install-' + plan.resolution | translate }} + } @else if (ws.reviewing && plan) { + {{ plannedOutcomeOf(plan) | translate }} } } } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.scss index 12306d9532..50cdc81b07 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.scss @@ -25,6 +25,12 @@ flex-direction: column; max-height: 90vh; + // The content takes the height left by the header and the actions, so a long form scrolls inside it + .mat-mdc-dialog-content { + flex: 1 1 auto; + min-height: 0; + } + @media #{$mat-lt-md} { max-height: 100%; height: 100%; @@ -49,8 +55,10 @@ flex: 1; padding: 0; } + // The current step fills the content area and scrolls itself: the stepper may give it overflow: hidden .mat-horizontal-stepper-content.mat-horizontal-stepper-content-current { height: 100%; + overflow-y: auto; } .mat-horizontal-stepper-header.mat-step-header { padding: 0 12px; @@ -329,8 +337,8 @@ font-weight: 500; line-height: 16px; letter-spacing: 0.4px; - color: #305680; - background: rgba(48, 86, 128, 0.08); + color: var(--tb-primary-500); + background: color-mix(in srgb, var(--tb-primary-500) 8%, transparent); border-radius: 4px; padding: 2px 8px; } @@ -348,6 +356,27 @@ color: #198038; } +// Update: the outcome of a row shows in when the row gets it +.tb-update-reveal { + display: inline-block; + animation: tb-update-reveal 200ms ease-out; + + @media (prefers-reduced-motion: reduce) { + animation: none; + } +} + +@keyframes tb-update-reveal { + from { + opacity: 0; + transform: scale(0.6); + } + to { + opacity: 1; + transform: scale(1); + } +} + .tb-progress-status-progress { color: rgba(0, 0, 0, 0.54); } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts index f045cdbd71..ac73616893 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts @@ -68,7 +68,8 @@ export interface DeviceInstallDialogData { item: MpItemVersionView; reviewMode?: boolean; selectedInstallMethod?: string; - installState?: Record; + // Review mode: the installed package, whose install state the wizard shows + reviewed?: DeviceInstalledItemDescriptor; entityGroupId?: string; customerId?: string; // Set when the wizard updates an installed package to the item version @@ -197,7 +198,7 @@ export interface WizardStep { formFields?: FormFieldDefinition[]; // Fields the dialog adds on top of the package's form file extraFormFields?: FormFieldDefinition[]; - // Key of the step's form values in the install state; the label when not set + // Form: the key of its values in the install state stateKey?: string; // Update: the keys of the form's fields the installed version didn't have newFieldKeys?: Set; @@ -224,6 +225,8 @@ export interface ConnectionCheck { } const ENTITY_STEP_MIN_DELAY = 2000; +// Update: the rows show the outcome of the one request one after another, this far apart +const UPDATE_REVEAL_INTERVAL = 150; // Where the wizard keeps the converter it builds for a step with "default": true, as if the package had that file const DEFAULT_CONVERTER_PATH = 'tb-default-converter/'; const DEFAULT_RANDOM_SIZE = 20; @@ -462,10 +465,10 @@ export class TbDeviceInstallDialogComponent extends DialogComponent, withFormValues = true): void { - for (const [stepName, data] of Object.entries(installState)) { - if (withFormValues && data.formValues) { - Object.assign(this.formValues, data.formValues); - } - if (data.entityOutput) { - // Find the step type alias from the raw steps to set the correct entity output key - const rawSteps = this.packageInfo.installSteps[this.selectedInstallMethod] || []; - const matchingStep = rawSteps.find(s => this.stateKeysOf(s).includes(stepName)) ?? - // Update: a step the new version renamed or gave an id - (this.data.update ? rawSteps.find(s => this.storedStateOf(s)?.key === stepName) : undefined); - if (matchingStep) { - const alias = stepTypeAliasMap[matchingStep.type]; - if (alias) { - this.entityOutputs.set(alias, data.entityOutput); - } - } + /** + * Takes the installed package's form values and the outputs of its entity steps, by alias. + * withFormValues false: only the entity outputs, e.g. to keep the values the user has just entered. + */ + private restoreInstallState(withFormValues = true): void { + if (withFormValues) { + for (const state of Object.values(this.installedDescriptor?.installState ?? {})) { + Object.assign(this.formValues, state?.formValues); + } + } + for (const step of this.packageInfo.installSteps[this.selectedInstallMethod] || []) { + const alias = stepTypeAliasMap[step.type]; + const output = alias ? this.storedStateOf(step)?.state.entityOutput : undefined; + if (output) { + this.entityOutputs.set(alias, output); } } } @@ -1088,7 +1088,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent | undefined; if (this.reviewMode) { - storedValues = this.data.installState?.[ws.stateKey ?? ws.label]?.formValues; + storedValues = this.installedDescriptor.installState[ws.stateKey]?.formValues; } else if (this.data.update && ws.stateKey !== TRANSPORT_STEP_STATE_KEY && ws.rawSteps[0]) { // Also when the new version renamed the step storedValues = this.storedStateOf(ws.rawSteps[0])?.state.formValues; @@ -1462,15 +1462,12 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { - const alias = stepTypeAliasMap[s.type]; - const output = alias ? this.entityOutputs.get(alias) : null; - const key = this.stateKeysOf(s).find(k => this.data.installState?.[k]); - const storedState = key ? this.data.installState[key] : undefined; + const storedState = this.storedStateOf(s)?.state; return { step: s, status: 'success' as const, resolvedName: this.resolveVariables(s.name), - entityOutput: output || undefined, + entityOutput: storedState?.entityOutput, resolution: storedState?.resolution || 'created' }; }); @@ -1507,6 +1504,12 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { + const duplicateKey = this.duplicateStateKey(); + if (duplicateKey) { + ws.progressError = this.translate.instant('iot-hub.device-install-duplicate-step', { key: duplicateKey }); + this.cdr.detectChanges(); + return; + } for (const ep of ws.entitySteps) { if (ep.status === 'success') { continue; @@ -1943,7 +1946,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent | undefined { - this.restoreInstallState(this.data.update.descriptor.installState ?? {}); + this.restoreInstallState(); try { return this.integrationMetadataOf(step); } finally { @@ -2121,12 +2124,27 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { ws.reviewing = false; @@ -2175,23 +2194,27 @@ export class TbDeviceInstallDialogComponent extends DialogComponent 0 && interval) { + await this.delay(interval); + } + const output = result.outputs?.[this.stateKeyOf(ep.step)]; const plan = this.entityPlans.get(ep); const resolution = plan?.previous?.resolution ?? plan?.resolution ?? 'created'; if (output) { @@ -2202,8 +2225,10 @@ export class TbDeviceInstallDialogComponent extends DialogComponent = {}; for (const ws of this.wizardSteps) { if (ws.type === 'form' && ws.formGroup) { - state[ws.stateKey ?? ws.label] = { formValues: ws.formGroup.getRawValue() }; + state[ws.stateKey] = { formValues: ws.formGroup.getRawValue() }; } } return state; @@ -2402,7 +2427,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { - this.restoreInstallState(this.data.update.descriptor.installState ?? {}); + this.restoreInstallState(); let ownDefaultConverterIds: Set | undefined; try { for (const step of this.packageInfo.installSteps[this.selectedInstallMethod] ?? []) { @@ -2446,7 +2471,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { if (step.type === InstallStepType.SHOW_FORM) { @@ -2491,7 +2516,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent created.id === id) && !usedExisting; } - /** The keys the install state may keep a step under: its id, or else its name, as written or resolved. */ - private stateKeysOf(step: DeviceInstallStep): string[] { - return step.id ? [step.id] : [step.name, this.resolveVariables(step.name)]; + /** The installed package: the one the wizard updates, or the one review mode shows. */ + private get installedDescriptor(): DeviceInstalledItemDescriptor | undefined { + return this.data.update?.descriptor ?? this.data.reviewed; + } + + /** + * The key of the step's install state: its id, or else its type and name, so that two steps of an install method + * never share it. A form keeps its name: it records no entity, and no entity step's key equals it. + * The server keys the steps of an update the same way. + */ + private stateKeyOf(step: DeviceInstallStep): string { + return step.id ?? (step.type === InstallStepType.SHOW_FORM ? step.name : `${step.type}:${step.name}`); + } + + /** A key two steps of the install method share, so one's install state would overwrite the other's; null when none. */ + private duplicateStateKey(): string | null { + const keys = new Set(); + for (const step of this.packageInfo.installSteps[this.selectedInstallMethod] ?? []) { + if (step.type !== InstallStepType.SHOW_FORM && !ENTITY_STEP_TYPES.has(step.type)) { + continue; + } + const key = this.stateKeyOf(step); + if (keys.has(key)) { + return key; + } + keys.add(key); + } + return null; } /** - * Update: the install state of a step of the new version, under the key of the installed step it replaces. + * The installed package's install state of a step; in an update, under the key of the installed step it replaces. * Without the installed version's steps (e.g. it can't be downloaded any more), a step that has gained an id - * is also looked up under its own name, which the installed version keyed it by. + * is also looked up as the installed version had it, without the id. */ private storedStateOf(step: DeviceInstallStep): { key: string; state: any } | undefined { - const installState = this.data.update?.descriptor.installState ?? {}; - const previousStep = this.findPreviousStep(step); - const keys = [...(previousStep ? this.stateKeysOf(previousStep) : []), ...this.stateKeysOf(step)]; - if (!this.previousPackageInfo && step.id) { - keys.push(step.name, this.resolveVariables(step.name)); - } - const key = keys.find(k => k && installState[k]); - return key ? { key, state: installState[key] } : undefined; + const installState = this.installedDescriptor?.installState ?? {}; + const steps = [this.findPreviousStep(step), step, + this.data.update && !this.previousPackageInfo && step.id ? { ...step, id: undefined } : undefined] + .filter((s): s is DeviceInstallStep => !!s); + const key = steps.map(s => this.stateKeyOf(s)).find(k => installState[k]); + if (key) { + return { key, state: installState[key] }; + } + // Legacy: an entity step without an id was keyed by its name, as written or resolved, so a later step of the same + // name overwrote its state. Such a state is the step's only when it records an entity of the step's type. + const entityType = this.stepTypeToEntityType(step.type); + const legacyKey = steps.filter(s => !s.id && s.type !== InstallStepType.SHOW_FORM) + .flatMap(s => [s.name, this.resolveVariables(s.name)]) + .find(k => installState[k] && this.installedDescriptor.createdEntityIds?.some( + created => created.id === installState[k].entityOutput?.id && created.entityType === entityType)); + return legacyKey ? { key: legacyKey, state: installState[legacyKey] } : undefined; } private formStepChanged(step: DeviceInstallStep): boolean { @@ -2651,7 +2709,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { const run = ++this.updateCheckRun; // Templates refer to the package's entities, e.g. ${deviceProfile.id}: until the steps run, the installed ones - this.restoreInstallState(this.data.update.descriptor.installState ?? {}, false); + this.restoreInstallState(false); ws.entitySteps = ws.rawSteps.map(s => ({ step: s, status: 'pending' as const, @@ -2842,12 +2900,12 @@ export class TbDeviceInstallDialogComponent extends DialogComponent = {}; for (const ws of this.wizardSteps) { if (ws.type === 'form' && ws.formGroup) { - state[ws.stateKey ?? ws.label] = { formValues: ws.formGroup.getRawValue() }; + state[ws.stateKey] = { formValues: ws.formGroup.getRawValue() }; } else if (ws.type === 'progress' && ws.entitySteps) { for (const ep of ws.entitySteps) { if (ep.status === 'success' && ep.entityOutput) { const metadata = this.addedMetadataOf(ep.step); - state[ep.step.id ?? ep.step.name] = { entityOutput: ep.entityOutput, resolution: ep.resolution || 'created', + state[this.stateKeyOf(ep.step)] = { entityOutput: ep.entityOutput, resolution: ep.resolution || 'created', ...(ep.step.default ? { defaultConverter: true } : {}), ...(metadata ? { metadata } : {}) }; } } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts index 46fed1fbae..9c5d995c10 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts @@ -239,7 +239,7 @@ export class IotHubActionsService { return this.openDeviceInstallDialog(item, { reviewMode: true, selectedInstallMethod: deviceDescriptor.selectedInstallMethod, - installState: deviceDescriptor.installState + reviewed: deviceDescriptor }); } @@ -265,7 +265,7 @@ export class IotHubActionsService { } private openDeviceInstallDialog(item: MpItemVersionView, - options?: { reviewMode?: boolean; selectedInstallMethod?: string; installState?: any; + options?: { reviewMode?: boolean; selectedInstallMethod?: string; reviewed?: DeviceInstalledItemDescriptor; entityGroupId?: string; customerId?: string; update?: DeviceInstallUpdate}): Observable { return this.dialog.open(TbDeviceInstallDialogComponent, { panelClass: ['tb-dialog', 'tb-fullscreen-dialog-lt-md'], diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-default-converter.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-default-converter.ts index 0a6f970e21..5db81a5b50 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-default-converter.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-default-converter.ts @@ -113,6 +113,7 @@ export const defaultConverterUpdateRequest = (update: DefaultConverterUpdate, ex installState: {}, steps: [{ name: update.converter.name, + // The server keys the step's state by its id: the state stays under the key it has id: update.stateKey, type: 'UPLINK_CONVERTER', action: 'OVERWRITE', diff --git a/ui-ngx/src/app/shared/models/iot-hub/device-package.models.ts b/ui-ngx/src/app/shared/models/iot-hub/device-package.models.ts index 088f787440..d204428919 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/device-package.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/device-package.models.ts @@ -216,7 +216,7 @@ export interface DeviceInstallStep { type: InstallStepType; name: string; // Optional stable id of the step, unique within the install method: the key of the step's install state, - // so the next version can rename the step. Without it, the name is the key. + // so the next version can rename the step. Without it, the key is the type and the name; a form's is its name. id?: string; file?: string; template?: string; diff --git a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts index 2ca0603a37..49c5dbf50d 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts @@ -62,7 +62,7 @@ export interface DeviceUpdateStep { serverAttributes?: any; sharedAttributes?: any; resolution?: string; - // The package step's id, which keys its install state; the name when not set + // The package step's stable id, so that a next version can rename the step id?: string; // INTEGRATION: the step's metadata entries, which a KEEP merges into the integration; null removes an entry metadata?: Record; @@ -80,12 +80,13 @@ export interface DeviceUpdateRequest { steps: DeviceUpdateStep[]; } -/** All of the update was applied, or none of it: failedStep names the step that failed, if one did. */ +/** All of the update was applied, or none of it: failedStep is the install state key of the step that failed, if one did. */ export interface DeviceUpdateResult { success: boolean; errorMessage?: string; failedStep?: string; descriptor?: DeviceInstalledItemDescriptor; + // By install state key of the step outputs?: Record; } diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index 2fcc9d2735..fe7490032a 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -6588,17 +6588,17 @@ "device-installing-title": "Installing \"{{name}}\"", "device-update-title": "Update \"{{name}}\"", "device-update-step": "Update", - "device-update-no-conflicts": "No conflicts", + "device-update-will-update": "Will be updated", + "device-update-will-create": "Will be created", + "device-update-no-changes": "No changes", "device-update-new": "New", "device-update-shared": "Used by other packages. The update affects them.", "device-update-new-default-converter": "ThingsBoard has a new version of the default converter used by this package.", "device-update-modified": "Has local changes. You can download the current version here.", "device-install-unexpected-error": "Something went wrong. Try again.", - "device-update-existing-use-existing": "Already exists. The existing one will be used.", - "device-update-existing-overwrite": "Already exists. It will be overwritten.", - "device-update-existing-create-copy": "Already exists. A copy will be created.", + "device-install-duplicate-step": "Two install steps of this device package have the same key: {{key}}. Report it to the package's creator.", "device-update-confirm-warnings": "Confirm { count, plural, =1 {1 warning} other {# warnings} } to enable Update", - "device-update-skipped": "Not changed", + "device-update-skipped": "Unchanged", "device-update-updated": "Updated", "device-update-created": "Created", "device-update-try-again": "Try again", From a8bc01f224c1bf0e074c7e03e0163b6bc2fc9b4e Mon Sep 17 00:00:00 2001 From: dshvaika Date: Thu, 12 Nov 2026 18:25:00 +0200 Subject: [PATCH 10/21] IoT Hub device packages: the duplicate step check leaves forms out, the step id comment says it is also the state key --- .../server/service/iot_hub/DeviceUpdateRequest.java | 3 ++- .../device-install-dialog.component.ts | 7 +++++-- .../shared/models/iot-hub/iot-hub-installed-item.models.ts | 3 ++- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java index 223c2eb723..a62f556c57 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java @@ -38,7 +38,8 @@ public class DeviceUpdateRequest { @Data public static class Step { private String name; - // The package step's stable id, so that a next version can rename the step + // The package step's stable id, so that a next version can rename the step. It is also the step's install state + // key when set, which the default converter update relies on to write the state back under the stored key private String id; // InstallStepType of the package: DEVICE_PROFILE, DEVICE, GATEWAY, GATEWAY_CONNECTOR, DASHBOARD, RULE_CHAIN, // UPLINK_CONVERTER, DOWNLINK_CONVERTER, INTEGRATION diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts index ac73616893..79cb97b0d3 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts @@ -2615,11 +2615,14 @@ export class TbDeviceInstallDialogComponent extends DialogComponent(); for (const step of this.packageInfo.installSteps[this.selectedInstallMethod] ?? []) { - if (step.type !== InstallStepType.SHOW_FORM && !ENTITY_STEP_TYPES.has(step.type)) { + if (!ENTITY_STEP_TYPES.has(step.type)) { continue; } const key = this.stateKeyOf(step); diff --git a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts index 49c5dbf50d..07fac4bf63 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts @@ -62,7 +62,8 @@ export interface DeviceUpdateStep { serverAttributes?: any; sharedAttributes?: any; resolution?: string; - // The package step's stable id, so that a next version can rename the step + // The package step's stable id, so that a next version can rename the step. When set it is also the step's install + // state key: the default converter update sends the stored key here to write the state back under it id?: string; // INTEGRATION: the step's metadata entries, which a KEEP merges into the integration; null removes an entry metadata?: Record; From cf94ef0e5afdb414ffe259afefd892958b0bc027 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Thu, 12 Nov 2026 18:29:38 +0200 Subject: [PATCH 11/21] IoT Hub device packages: the duplicate step check counts forms again, since a form's values are saved under its key --- .../device-install-dialog.component.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts index 79cb97b0d3..22e141c3ff 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts @@ -2608,7 +2608,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent(); for (const step of this.packageInfo.installSteps[this.selectedInstallMethod] ?? []) { - if (!ENTITY_STEP_TYPES.has(step.type)) { + if (step.type !== InstallStepType.SHOW_FORM && !ENTITY_STEP_TYPES.has(step.type)) { continue; } const key = this.stateKeyOf(step); From 8a71a82c3697cf3e71e1b0a813856dc78b45039a Mon Sep 17 00:00:00 2001 From: dshvaika Date: Thu, 12 Nov 2026 18:39:25 +0200 Subject: [PATCH 12/21] IoT Hub device packages: an update step may not share the key of a form, whose values are saved under it --- .../iot_hub/DefaultDevicePackageUpdateService.java | 3 ++- .../DefaultDevicePackageUpdateServiceTest.java | 14 ++++++++++++++ .../device-install-dialog.component.ts | 2 +- 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java index 47d9e64804..f4604beea4 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java @@ -209,7 +209,8 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i throw new IllegalArgumentException("The update has no steps"); } Set ownedIds = ownedIds(devicePackage.descriptor()); - Set stateKeys = new HashSet<>(); + // A form's values are saved under its key too, so an entity step may not share it + Set stateKeys = request.getInstallState() != null ? new HashSet<>(request.getInstallState().keySet()) : new HashSet<>(); for (DeviceUpdateRequest.Step step : request.getSteps()) { if (step.getName() == null || step.getAction() == null || !isKnownType(step.getType())) { throw new IllegalArgumentException("Invalid update step: " + step.getName()); diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java index 2ebf946bae..38595a0c71 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java @@ -497,6 +497,20 @@ class DefaultDevicePackageUpdateServiceTest { verify(transactionTemplate, never()).execute(any()); } + @Test + void stepWithTheKeyOfAForm_isRejected() { + DeviceUpdateRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId); + step.setId("Settings"); + DeviceUpdateRequest request = request(step); + request.setInstallState(Map.of("Settings", JacksonUtil.newObjectNode().set("formValues", JacksonUtil.newObjectNode().put("interval", 10)))); + + DeviceUpdateResult result = service.apply(user, installedItem.getId(), request); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getErrorMessage()).isEqualTo("Duplicate update step: Settings"); + verify(transactionTemplate, never()).execute(any()); + } + @Test void stepsOfOneNameAndAnotherType_eachKeepTheirOwnState() { // Installed when the state was keyed by name: the integration's state replaced the converter's diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts index 22e141c3ff..cf187de9dd 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts @@ -2609,7 +2609,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent Date: Thu, 12 Nov 2026 17:39:46 +0100 Subject: [PATCH 13/21] Address review of subscription lifecycle fix - Make TbAbstractSubCtx.stop() final and move cancellation into a protected onStop() hook, so subclasses cannot cancel outside the lifecycle lock. - Guard doFetchAlarms() instead of fetchAlarms(), so the refresh path through cleanupOldAlarms() is covered too. - Cancel dynamic-value subscriptions when an alarm count context stops. - Make the stop-waits-for-registration test deterministic by waiting for the stopper to queue on the lifecycle lock. --- .../TbAbstractEntityQuerySubCtx.java | 13 ++++--------- .../service/subscription/TbAbstractSubCtx.java | 10 +++++++++- .../subscription/TbAlarmCountSubCtx.java | 1 + .../subscription/TbAlarmDataSubCtx.java | 6 +++--- .../subscription/TbAlarmStatusSubCtx.java | 10 ++-------- .../subscription/TbAbstractSubCtxTest.java | 18 +++++++----------- 6 files changed, 26 insertions(+), 32 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/subscription/TbAbstractEntityQuerySubCtx.java b/application/src/main/java/org/thingsboard/server/service/subscription/TbAbstractEntityQuerySubCtx.java index be14bba1bb..f78a42e2e6 100644 --- a/application/src/main/java/org/thingsboard/server/service/subscription/TbAbstractEntityQuerySubCtx.java +++ b/application/src/main/java/org/thingsboard/server/service/subscription/TbAbstractEntityQuerySubCtx.java @@ -73,15 +73,10 @@ public abstract class TbAbstractEntityQuerySubCtx ex clearDynamicValueSubscriptions(); } - public void stop() { - lifecycleLock.lock(); - try { - super.stop(); - cancelTasks(); - clearSubscriptions(); - } finally { - lifecycleLock.unlock(); - } + @Override + protected void onStop() { + cancelTasks(); + clearSubscriptions(); } public void setAndResolveQuery(T query) { diff --git a/application/src/main/java/org/thingsboard/server/service/subscription/TbAbstractSubCtx.java b/application/src/main/java/org/thingsboard/server/service/subscription/TbAbstractSubCtx.java index fd36cac030..bff14641c4 100644 --- a/application/src/main/java/org/thingsboard/server/service/subscription/TbAbstractSubCtx.java +++ b/application/src/main/java/org/thingsboard/server/service/subscription/TbAbstractSubCtx.java @@ -79,15 +79,23 @@ public abstract class TbAbstractSubCtx { public abstract boolean isDynamic(); - public void stop() { + public final void stop() { lifecycleLock.lock(); try { stopped = true; + onStop(); } finally { lifecycleLock.unlock(); } } + /** + * Cancels this context's tasks and subscriptions. Called by {@link #stop()} with {@link #lifecycleLock} held and + * after {@code stopped} is set, so overrides must not take the lock themselves and must not register anything. + */ + protected void onStop() { + } + /** * Registers a subscription owned by this context. Refused when the context is stopped or when its websocket * session is no longer registered, so that a subscription cannot outlive the session that created it. diff --git a/application/src/main/java/org/thingsboard/server/service/subscription/TbAlarmCountSubCtx.java b/application/src/main/java/org/thingsboard/server/service/subscription/TbAlarmCountSubCtx.java index 4ea43af3ad..5d48dc57ef 100644 --- a/application/src/main/java/org/thingsboard/server/service/subscription/TbAlarmCountSubCtx.java +++ b/application/src/main/java/org/thingsboard/server/service/subscription/TbAlarmCountSubCtx.java @@ -66,6 +66,7 @@ public class TbAlarmCountSubCtx extends TbAbstractEntityQuerySubCtx { } public void fetchAlarms() { - if (stopped) { - return; - } alarmInvocationAttempts++; log.trace("[{}] Fetching alarms: {}", cmdId, alarmInvocationAttempts); if (alarmInvocationAttempts <= maxAlarmQueriesPerRefreshInterval) { @@ -99,6 +96,9 @@ public class TbAlarmDataSubCtx extends TbAbstractDataSubCtx { } private void doFetchAlarms() { + if (stopped) { + return; + } AlarmDataUpdate update; if (!entitiesMap.isEmpty()) { long start = System.currentTimeMillis(); diff --git a/application/src/main/java/org/thingsboard/server/service/subscription/TbAlarmStatusSubCtx.java b/application/src/main/java/org/thingsboard/server/service/subscription/TbAlarmStatusSubCtx.java index 4e537d8d49..87df1372de 100644 --- a/application/src/main/java/org/thingsboard/server/service/subscription/TbAlarmStatusSubCtx.java +++ b/application/src/main/java/org/thingsboard/server/service/subscription/TbAlarmStatusSubCtx.java @@ -43,14 +43,8 @@ public class TbAlarmStatusSubCtx extends TbAbstractSubCtx { } @Override - public void stop() { - lifecycleLock.lock(); - try { - super.stop(); - localSubscriptionService.cancelSubscription(getTenantId(), sessionRef.getSessionId(), subscription.getSubscriptionId()); - } finally { - lifecycleLock.unlock(); - } + protected void onStop() { + localSubscriptionService.cancelSubscription(getTenantId(), sessionRef.getSessionId(), subscription.getSubscriptionId()); } public void createSubscription(AlarmStatusCmd cmd) { diff --git a/application/src/test/java/org/thingsboard/server/service/subscription/TbAbstractSubCtxTest.java b/application/src/test/java/org/thingsboard/server/service/subscription/TbAbstractSubCtxTest.java index d0c7039b55..01ffe38317 100644 --- a/application/src/test/java/org/thingsboard/server/service/subscription/TbAbstractSubCtxTest.java +++ b/application/src/test/java/org/thingsboard/server/service/subscription/TbAbstractSubCtxTest.java @@ -9,8 +9,6 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.thingsboard.server.service.ws.WebSocketService; import org.thingsboard.server.service.ws.WebSocketSessionRef; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -81,9 +79,7 @@ public class TbAbstractSubCtxTest { when(wsService.hasSession(SESSION_ID)).thenReturn(true); CountDownLatch registrationEntered = new CountDownLatch(1); CountDownLatch releaseRegistration = new CountDownLatch(1); - List events = new CopyOnWriteArrayList<>(); willAnswer(invocation -> { - events.add("register"); registrationEntered.countDown(); releaseRegistration.await(10, TimeUnit.SECONDS); return null; @@ -93,19 +89,19 @@ public class TbAbstractSubCtxTest { registrar.start(); assertThat(registrationEntered.await(10, TimeUnit.SECONDS)).isTrue(); - Thread stopper = new Thread(() -> { - subCtx.stop(); - events.add("stop"); - }); + Thread stopper = new Thread(subCtx::stop); stopper.start(); - stopper.join(200); - assertThat(stopper.isAlive()).as("stop() must wait for the in-flight registration").isTrue(); + long deadline = System.currentTimeMillis() + 10_000; + while (!subCtx.lifecycleLock.hasQueuedThreads() && System.currentTimeMillis() < deadline) { + Thread.onSpinWait(); + } + assertThat(subCtx.lifecycleLock.hasQueuedThreads()).as("stop() must queue on the lifecycle lock").isTrue(); + assertThat(subCtx.isStopped()).as("stop() must not mark the context stopped while a registration holds the lock").isFalse(); releaseRegistration.countDown(); registrar.join(10_000); stopper.join(10_000); - assertThat(events).containsExactly("register", "stop"); assertThat(subCtx.isStopped()).isTrue(); subCtx.registerSubscription(subscription); From 58fe135737eb5b5c175a4f874025c62add5c8ce1 Mon Sep 17 00:00:00 2001 From: Vladyslav_Prykhodko Date: Thu, 12 Nov 2026 19:18:27 +0200 Subject: [PATCH 14/21] License header cache: a locked or failing cache no longer stops the check, pruning removes only its own files, CI keeps one signature - put() commits at once, so the write lock is held briefly; any SQLite error in open, get or put continues the run without the cache - a lock at open is no longer taken for damage, so the file of another run is not deleted; open() closes its connection on failure - pruning matches only <32 hex>.sqlite; LICENSE_HEADERS_CACHE_SIGNATURES sets how many signatures are kept, CI keeps 1 - the copy similarity threshold and the CRLF staging are each defined once - the save step takes the restore step's primary key; the workflow comment credits cache scoping - --cache is listed in the wrapper's usage --- .github/workflows/check-license-headers.yml | 11 +- check-license-headers.sh | 3 +- .../src/main/python/license-headers/README.md | 5 + .../license-headers/check_license_headers.py | 126 +++++++++++++----- .../test_check_license_headers.py | 121 ++++++++++++++--- 5 files changed, 212 insertions(+), 54 deletions(-) diff --git a/.github/workflows/check-license-headers.yml b/.github/workflows/check-license-headers.yml index 54da6cea99..d41aee380d 100644 --- a/.github/workflows/check-license-headers.yml +++ b/.github/workflows/check-license-headers.yml @@ -46,9 +46,12 @@ jobs: java-version: 21 cache: maven - # Header-free CE contents from earlier runs. A pull request reads the cache of its base branch, then of master; - # only pushes and manual runs write one, so a pull request never feeds the cache that other runs trust. + # Header-free CE contents from earlier runs. A pull request reads the cache of its base branch, then of master. + # What keeps a pull request from feeding the cache that other runs trust is GitHub's cache scoping, not the `if:` + # on the save step: a pull request runs its own copy of this workflow, and whatever it saved would be restorable + # only by that pull request. The `if:` keeps pull requests from spending the repository's cache storage. - name: Restore normalized CE contents + id: restore-cache uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: target/license-headers-cache @@ -68,6 +71,8 @@ jobs: # The runner does nothing else: use every CPU, not all but one as on a workstation. LICENSE_HEADERS_JOBS="$(nproc)" export LICENSE_HEADERS_JOBS + # A run uses the cache of one signature; older ones would only make every save and restore larger. + export LICENSE_HEADERS_CACHE_SIGNATURES=1 ./check-license-headers.sh ${SINCE:+--since "$SINCE"} 2>&1 | tee target/license-provenance/console.log # Saved even when the check finds problems, but only when the run normalized something the cache lacked. @@ -78,7 +83,7 @@ jobs: uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: target/license-headers-cache - key: license-headers-ce-v1-${{ github.ref_name }}-${{ github.run_id }} + key: ${{ steps.restore-cache.outputs.cache-primary-key }} - name: Add findings to the job summary if: failure() && hashFiles('target/license-provenance/console.log') != '' diff --git a/check-license-headers.sh b/check-license-headers.sh index bcfba4f999..f101e2c3dc 100755 --- a/check-license-headers.sh +++ b/check-license-headers.sh @@ -8,13 +8,14 @@ set -euo pipefail usage() { echo "Checks SPDX license headers against CE provenance." - echo "usage: $0 [--fix] [--since ] [--ce-ref ] [--ce-remote ] [--output target/...] [--no-cache]" + echo "usage: $0 [--fix] [--since ] [--ce-ref ] [--ce-remote ] [--output target/...] [--no-cache] [--cache ]" echo " --fix restamp files whose expected header the check determined" echo " and remove redundant or orphaned curations" echo " --since check only files changed since the merge base of and HEAD," echo " uncommitted and untracked files included, e.g. --since origin/lts-4.4;" echo " runs the full check when CE commits, Mycila settings or the check itself changed" echo " --no-cache normalize every CE file again instead of reusing target/license-headers-cache" + echo " --cache keep the cache in instead of target/license-headers-cache" echo " --ce-ref CE branch, tag or commit that this branch integrates, fetched on every run;" echo " without it, CE is the history that does not contain the relicensing commit" echo " --ce-remote CE repository to fetch --ce-ref from (default: https://github.com/thingsboard/thingsboard.git)" diff --git a/tools/src/main/python/license-headers/README.md b/tools/src/main/python/license-headers/README.md index 9f854b548a..efe877b050 100644 --- a/tools/src/main/python/license-headers/README.md +++ b/tools/src/main/python/license-headers/README.md @@ -49,9 +49,14 @@ while the Mycila version and configuration in the root `pom.xml`, the templates and the check itself stay the same; anything else starts a new cache, and the check normalizes again instead of using the old one. Pass `--no-cache` to normalize every CE file again, or `--cache` to keep the cache elsewhere. +The check keeps the caches of the three most recent signatures, so switching +between branches does not start over; set `LICENSE_HEADERS_CACHE_SIGNATURES` +to keep another number. If SQLite cannot use the cache, for example because +another run holds its lock, the run continues without it. In GitHub Actions, pushes and manual runs save the cache and pull requests only read it: a pull request takes the cache of its base branch, then of `master`. +CI keeps only the current signature, so the saved cache holds one database. ## Check only changed files diff --git a/tools/src/main/python/license-headers/check_license_headers.py b/tools/src/main/python/license-headers/check_license_headers.py index 8839a59f8d..9010e252d1 100644 --- a/tools/src/main/python/license-headers/check_license_headers.py +++ b/tools/src/main/python/license-headers/check_license_headers.py @@ -71,10 +71,14 @@ REPEATED_HEADERS = 3 HEADER_WINDOW = 4096 XML_SPACE = "{http://www.w3.org/XML/1998/namespace}space" JOBS_VARIABLE = "LICENSE_HEADERS_JOBS" +CACHE_SIGNATURES_VARIABLE = "LICENSE_HEADERS_CACHE_SIGNATURES" CACHE_DIRECTORY = "target/license-headers-cache" CACHE_FORMAT = "1" CACHE_UPDATED = ".updated" CACHE_SIGNATURES_KEPT = 3 +CACHE_FILE = re.compile(r"[0-9a-f]{32}\.sqlite") +# Git's minimum similarity for a copy, in percent: the -C threshold and the size filter in front of it. +COPY_SIMILARITY = 50 @dataclass(frozen=True) @@ -142,14 +146,18 @@ class Console: console = Console() +def positive_setting(variable, default): + configured = os.environ.get(variable, "") + if not configured: + return default + if not configured.isdigit() or int(configured) < 1: + raise Failure(f"{variable} must be a positive number, not {configured!r}") + return int(configured) + + def jobs(): """Parallel subprocesses: LICENSE_HEADERS_JOBS when set, otherwise all CPUs but one to keep the machine responsive.""" - configured = os.environ.get(JOBS_VARIABLE, "") - if configured: - if not configured.isdigit() or int(configured) < 1: - raise Failure(f"{JOBS_VARIABLE} must be a positive number, not {configured!r}") - return int(configured) - return max(1, (os.cpu_count() or 1) - 1) + return positive_setting(JOBS_VARIABLE, max(1, (os.cpu_count() or 1) - 1)) def parallel(function, items): @@ -766,7 +774,7 @@ def normalized_copies(mycila, source_refs, names, nonempty): before = stage(mycila, sources) after = stage(mycila, destinations) raw = git(mycila.root, "diff-tree", "--no-commit-id", "-r", "--raw", "--no-abbrev", "-z", - "-C50%", "--find-copies-harder", "-l0", before, after) + f"-C{COPY_SIMILARITY}%", "--find-copies-harder", "-l0", before, after) keys = {path: key for key, path in mycila.paths.items()} copies = defaultdict(list) for source, destination, similarity in parse_copies(raw): @@ -778,9 +786,14 @@ def normalized_copies(mycila, source_refs, names, nonempty): return dict(copies) +def staged(content): + """What stage() hands to Git: the size filter in front of the copy search measures exactly this.""" + return content.replace(b"\r\n", b"\n") + + def stage(mycila, keys): for key in keys: - mycila.write(key, mycila.contents[key].replace(b"\r\n", b"\n")) + mycila.write(key, staged(mycila.contents[key])) pathspec = "".join(mycila.paths[key] + "\0" for key in sorted(keys)).encode("utf-8") run(["git", "--literal-pathspecs", "add", "-f", "--pathspec-from-file=-", "--pathspec-file-nul"], mycila.root, data=pathspec) @@ -913,35 +926,61 @@ class Comparison: class NormalizationCache: """Header-free contents of CE inputs from earlier runs, keyed by content and file name (Mycila styles follow the - name). One SQLite file per normalization signature: a different Mycila setup, template or check misses the cache.""" + name). One SQLite file per normalization signature: a different Mycila setup, template or check misses the cache. + The cache only ever costs or saves time: when SQLite fails, the run continues without it.""" def __init__(self, directory, signature): self.directory = directory self.lock = threading.Lock() self.added = 0 self.hits = 0 + self.database = None + self.unavailable = None directory.mkdir(parents=True, exist_ok=True) (directory / CACHE_UPDATED).unlink(missing_ok=True) self.path = directory / f"{signature}.sqlite" try: - self.database = self.open() - except sqlite3.DatabaseError: - # A damaged cache only costs time: start it again instead of failing the check. - self.path.unlink() - self.database = self.open() + try: + self.database = self.open() + except sqlite3.OperationalError: + raise # locked by another run or unreadable: not damage, so the file stays + except sqlite3.DatabaseError: + # A damaged cache only costs time: start it again instead of failing the check. + self.path.unlink() + self.database = self.open() + except sqlite3.Error as exc: + self.disable(exc) + return os.utime(self.path) - for stale in sorted(directory.glob("*.sqlite"), key=lambda path: path.stat().st_mtime)[:-CACHE_SIGNATURES_KEPT]: + # Only files named like this cache's own: --cache may point at a directory that holds other SQLite files. + own = [path for path in directory.iterdir() if CACHE_FILE.fullmatch(path.name)] + kept = positive_setting(CACHE_SIGNATURES_VARIABLE, CACHE_SIGNATURES_KEPT) + for stale in sorted(own, key=lambda path: path.stat().st_mtime)[:-kept]: stale.unlink() def open(self): database = sqlite3.connect(self.path, check_same_thread=False) - database.execute("CREATE TABLE IF NOT EXISTS normalized (input TEXT PRIMARY KEY, content BLOB NOT NULL)") - # Opening reads only the schema: a file damaged below it would fail on the first lookup instead. - if database.execute("PRAGMA quick_check").fetchone()[0] != "ok": - database.close() - raise sqlite3.DatabaseError(f"{self.path} is damaged") + try: + database.execute("CREATE TABLE IF NOT EXISTS normalized (input TEXT PRIMARY KEY, content BLOB NOT NULL)") + # Opening reads only the schema: a file damaged below it would fail on the first lookup instead. + if database.execute("PRAGMA quick_check").fetchone()[0] != "ok": + raise sqlite3.DatabaseError(f"{self.path} is damaged") + except BaseException: + database.close() # before any unlink: Windows cannot remove an open file + raise return database + def disable(self, exc): + """Continues the run without the cache; what earlier puts committed stays valid. Reported by close(), so + that a progress line in the middle of the run stays intact.""" + self.unavailable = self.unavailable or str(exc) + if self.database is not None: + try: + self.database.close() + except sqlite3.Error: + pass + self.database = None + @staticmethod def input(name, raw): return hashlib.sha256(raw).hexdigest() + "/" + PurePosixPath(name).name @@ -949,25 +988,43 @@ class NormalizationCache: def get(self, inputs): found = {} with self.lock: - for key, raw in inputs.items(): - row = self.database.execute("SELECT content FROM normalized WHERE input = ?", - (self.input(key[0], raw),)).fetchone() - if row is not None: - found[key] = bytes(row[0]) + if self.database is None: + return found + try: + for key, raw in inputs.items(): + row = self.database.execute("SELECT content FROM normalized WHERE input = ?", + (self.input(key[0], raw),)).fetchone() + if row is not None: + found[key] = bytes(row[0]) + except sqlite3.Error as exc: + self.disable(exc) + return {} self.hits += len(found) return found def put(self, entries): with self.lock: - self.database.executemany("INSERT OR IGNORE INTO normalized VALUES (?, ?)", - [(self.input(key[0], raw), content) for key, raw, content in entries]) + if self.database is None: + return + try: + self.database.executemany("INSERT OR IGNORE INTO normalized VALUES (?, ?)", + [(self.input(key[0], raw), content) for key, raw, content in entries]) + # Committed at once: the write lock is held only briefly, so another run on the same cache can add too. + self.database.commit() + except sqlite3.Error as exc: + self.disable(exc) + return self.added += len(entries) def close(self): - self.database.commit() - self.database.close() + if self.database is not None: + self.database.close() + self.database = None if self.added: (self.directory / CACHE_UPDATED).touch() + if self.unavailable: + console.line(f"The cache in {self.directory} was unavailable ({self.unavailable}); " + "the run continued without it", "dim") class NoCache: @@ -1011,17 +1068,18 @@ def normalize(repo, plugin, cache, inputs): def staged_size(content): - return len(content.replace(b"\r\n", b"\n")) + return len(staged(content)) def could_be_copy(size, destinations): - """Git scores a pair 0 unless the smaller blob is at least half the larger (diffcore-rename estimate_similarity).""" - return any(2 * min(size, other) >= max(size, other) for other in destinations) + """Git scores a pair 0 unless the smaller blob is at least COPY_SIMILARITY % of the larger (diffcore-rename + estimate_similarity).""" + return any(100 * min(size, other) >= COPY_SIMILARITY * max(size, other) for other in destinations) def could_shrink_to_copy(raw_size, destinations): - """Normalizing never grows a file: below half the smallest destination it stays out of Git's reach.""" - return 2 * raw_size >= min(destinations) + """Normalizing never grows a file: below COPY_SIMILARITY % of the smallest destination it stays out of Git's reach.""" + return 100 * raw_size >= COPY_SIMILARITY * min(destinations) def compare(repo, plugin, lineage, contents, cache, in_scope): diff --git a/tools/src/main/python/license-headers/test_check_license_headers.py b/tools/src/main/python/license-headers/test_check_license_headers.py index 72e21499be..c1e5bbe2bb 100644 --- a/tools/src/main/python/license-headers/test_check_license_headers.py +++ b/tools/src/main/python/license-headers/test_check_license_headers.py @@ -4,9 +4,11 @@ # from contextlib import redirect_stderr, redirect_stdout +import hashlib import io import json import os +import sqlite3 from pathlib import Path import tempfile import textwrap @@ -17,6 +19,19 @@ import xml.etree.ElementTree as ET import check_license_headers as p +CONNECT = sqlite3.connect + + +def impatient_sqlite(): + """SQLite that waits 0.1 s instead of 5 s for another connection's lock.""" + return patch.object(sqlite3, "connect", lambda *args, **kwargs: CONNECT(*args, **kwargs | {"timeout": 0.1})) + + +def signature(label): + """A cache signature as cache_signature() shapes it: 32 hex characters.""" + return hashlib.sha256(label.encode()).hexdigest()[:32] + + def temporary_directory(test): directory = tempfile.TemporaryDirectory() test.addCleanup(directory.cleanup) @@ -1300,7 +1315,7 @@ class CacheTests(unittest.TestCase): self.assertEqual(shutil_tree, sorted(path.name for path in self.cache().iterdir())) def test_entries_are_keyed_by_content_and_file_name(self): - cache = p.NormalizationCache(temporary_directory(self), "signature") + cache = p.NormalizationCache(temporary_directory(self), signature("signature")) cache.put([(("A.java", "a"), b"// header\nbody\n", b"body\n")]) self.assertEqual({("moved/A.java", "b"): b"body\n"}, cache.get({("moved/A.java", "b"): b"// header\nbody\n"})) self.assertEqual({}, cache.get({("B.java", "b"): b"// header\nbody\n"})) @@ -1326,56 +1341,130 @@ class CacheTests(unittest.TestCase): def test_only_recent_signatures_are_kept_and_the_update_mark_is_fresh(self): directory = temporary_directory(self) for index in range(p.CACHE_SIGNATURES_KEPT + 2): - stale = directory / f"old{index}.sqlite" + stale = directory / f"{signature(f'old{index}')}.sqlite" stale.write_bytes(b"") os.utime(stale, (index, index)) (directory / p.CACHE_UPDATED).touch() - cache = p.NormalizationCache(directory, "current") + cache = p.NormalizationCache(directory, signature("current")) self.assertFalse((directory / p.CACHE_UPDATED).exists()) kept = sorted(path.name for path in directory.glob("*.sqlite")) self.assertEqual(p.CACHE_SIGNATURES_KEPT, len(kept)) - self.assertIn("current.sqlite", kept) + self.assertIn(f"{signature('current')}.sqlite", kept) cache.close() self.assertFalse((directory / p.CACHE_UPDATED).exists()) def test_a_damaged_cache_is_started_again(self): directory = temporary_directory(self) - (directory / "damaged.sqlite").write_bytes(b"not a database, cut off by a failed restore") - cache = p.NormalizationCache(directory, "damaged") + (directory / f"{signature('damaged')}.sqlite").write_bytes(b"not a database, cut off by a failed restore") + cache = p.NormalizationCache(directory, signature("damaged")) self.assertEqual({}, cache.get({("A.java", "a"): b"raw"})) cache.put([(("A.java", "a"), b"raw", b"normalized")]) cache.close() self.assertEqual({("A.java", "a"): b"normalized"}, - p.NormalizationCache(directory, "damaged").get({("A.java", "a"): b"raw"})) + p.NormalizationCache(directory, signature("damaged")).get({("A.java", "a"): b"raw"})) def test_a_cache_damaged_after_its_schema_is_started_again(self): directory = temporary_directory(self) - cache = p.NormalizationCache(directory, "damaged") + cache = p.NormalizationCache(directory, signature("damaged")) cache.put([((f"F{index}.java", "a"), f"raw {index}".encode(), b"normalized" * 400) for index in range(300)]) cache.close() - database = directory / "damaged.sqlite" + database = directory / f"{signature('damaged')}.sqlite" page = 4096 with database.open("r+b") as file: # The schema and the root pages stay readable, so the file opens; every lookup below them fails. file.seek(4 * page) file.write(b"\xff" * (database.stat().st_size - 4 * page)) - cache = p.NormalizationCache(directory, "damaged") + cache = p.NormalizationCache(directory, signature("damaged")) self.assertEqual({}, cache.get({("F0.java", "a"): b"raw 0"})) cache.put([(("A.java", "a"), b"raw", b"normalized")]) cache.close() self.assertEqual({("A.java", "a"): b"normalized"}, - p.NormalizationCache(directory, "damaged").get({("A.java", "a"): b"raw"})) + p.NormalizationCache(directory, signature("damaged")).get({("A.java", "a"): b"raw"})) def test_the_cache_of_a_branch_checked_long_ago_survives_newer_signatures(self): directory = temporary_directory(self) - p.NormalizationCache(directory, "revisited").close() - os.utime(directory / "revisited.sqlite", (1, 1)) + p.NormalizationCache(directory, signature("revisited")).close() + os.utime(directory / f"{signature('revisited')}.sqlite", (1, 1)) for index in range(p.CACHE_SIGNATURES_KEPT): - (directory / f"newer{index}.sqlite").write_bytes(b"") - cache = p.NormalizationCache(directory, "revisited") + (directory / f"{signature(f'newer{index}')}.sqlite").write_bytes(b"") + cache = p.NormalizationCache(directory, signature("revisited")) cache.put([(("A.java", "a"), b"raw", b"normalized")]) cache.close() - self.assertTrue((directory / "revisited.sqlite").exists()) + self.assertTrue((directory / f"{signature('revisited')}.sqlite").exists()) + + def test_pruning_leaves_files_the_cache_did_not_create(self): + directory = temporary_directory(self) + foreign = [directory / name for name in ("notes.sqlite", "ABCDEF0123456789ABCDEF0123456789.sqlite", "other.db")] + for path in foreign: + path.write_bytes(b"") + os.utime(path, (1, 1)) + for index in range(p.CACHE_SIGNATURES_KEPT): + (directory / f"{signature(f'newer{index}')}.sqlite").write_bytes(b"") + p.NormalizationCache(directory, signature("current")).close() + self.assertTrue(all(path.exists() for path in foreign)) + self.assertEqual(p.CACHE_SIGNATURES_KEPT, len([path for path in directory.iterdir() + if p.CACHE_FILE.fullmatch(path.name)])) + + def test_the_number_of_signatures_kept_can_be_set(self): + directory = temporary_directory(self) + for index in range(2): + stale = directory / f"{signature(f'old{index}')}.sqlite" + stale.write_bytes(b"") + os.utime(stale, (index, index)) + with patch.dict(os.environ, {p.CACHE_SIGNATURES_VARIABLE: "1"}): + p.NormalizationCache(directory, signature("current")).close() + self.assertEqual([f"{signature('current')}.sqlite"], [path.name for path in directory.glob("*.sqlite")]) + with patch.dict(os.environ, {p.CACHE_SIGNATURES_VARIABLE: "0"}), self.assertRaises(p.Failure): + p.NormalizationCache(directory, signature("current")) + + def test_entries_are_committed_at_once_so_another_run_can_add_its_own(self): + directory = temporary_directory(self) + first = p.NormalizationCache(directory, signature("shared")) + second = p.NormalizationCache(directory, signature("shared")) + first.put([(("A.java", "a"), b"raw a", b"a")]) + second.put([(("B.java", "b"), b"raw b", b"b")]) + self.assertEqual({("B.java", "b"): b"b"}, first.get({("B.java", "b"): b"raw b"})) + self.assertEqual({("A.java", "a"): b"a"}, second.get({("A.java", "a"): b"raw a"})) + first.close() + second.close() + + def test_a_cache_locked_by_another_run_is_skipped_and_kept(self): + directory = temporary_directory(self) + path = directory / f"{signature('locked')}.sqlite" + p.NormalizationCache(directory, signature("locked")).close() + other = sqlite3.connect(path, timeout=0) + other.execute("BEGIN EXCLUSIVE") + try: + with impatient_sqlite(): + cache = p.NormalizationCache(directory, signature("locked")) + self.assertEqual({}, cache.get({("A.java", "a"): b"raw"})) + cache.put([(("A.java", "a"), b"raw", b"normalized")]) + output = io.StringIO() + with redirect_stderr(output): + cache.close() + self.assertIn("continued without it", output.getvalue()) + self.assertFalse((directory / p.CACHE_UPDATED).exists()) + finally: + other.rollback() + other.close() + self.assertTrue(path.exists()) + + def test_a_lock_after_opening_downgrades_the_run_to_no_cache(self): + directory = temporary_directory(self) + path = directory / f"{signature('busy')}.sqlite" + with impatient_sqlite(): + cache = p.NormalizationCache(directory, signature("busy")) + other = sqlite3.connect(path, timeout=0) + other.execute("BEGIN EXCLUSIVE") + try: + cache.put([(("A.java", "a"), b"raw", b"normalized")]) + self.assertEqual({}, cache.get({("A.java", "a"): b"raw"})) + with redirect_stderr(io.StringIO()): + cache.close() + finally: + other.rollback() + other.close() + self.assertEqual(0, cache.added) @unittest.skipUnless(os.environ.get("LICENSE_HEADERS_MAVEN_TESTS") == "1", "opt-in Maven fixtures") From 5de9c90f53d1dd8ba9dd20bbb1557bc7e5d93c1a Mon Sep 17 00:00:00 2001 From: Vladyslav_Prykhodko Date: Thu, 12 Nov 2026 19:32:14 +0200 Subject: [PATCH 15/21] License header cache: CI saves it when its contents changed, without a marker; copy_candidates returns the hashes it adds - the workflow fingerprints the restored databases and saves only when the run changed them, so a check that fails before opening the cache, --no-cache or a run that only reads it saves nothing; the .updated marker and both of its clean-ups are gone - a test pins that a run which only reads the cache leaves its bytes unchanged - copy_candidates returns the comparison hashes of the CE files it searched instead of updating the caller's dict --- .github/workflows/check-license-headers.yml | 14 +++++++++---- .../src/main/python/license-headers/README.md | 3 ++- .../license-headers/check_license_headers.py | 21 ++++++++----------- .../test_check_license_headers.py | 13 ++++++------ 4 files changed, 27 insertions(+), 24 deletions(-) diff --git a/.github/workflows/check-license-headers.yml b/.github/workflows/check-license-headers.yml index d41aee380d..96e0e96e46 100644 --- a/.github/workflows/check-license-headers.yml +++ b/.github/workflows/check-license-headers.yml @@ -60,14 +60,19 @@ jobs: license-headers-ce-v1-${{ github.base_ref || github.ref_name }}- license-headers-ce-v1- + # What the restore brought, to save the cache below only when this run changed it. A run that only reads the + # cache leaves its bytes as they were; the check needs no marker for this. + - name: Fingerprint restored CE contents + id: cache-fingerprint + if: github.event_name != 'pull_request' + run: echo "hash=${{ hashFiles('target/license-headers-cache/*.sqlite') }}" >> "$GITHUB_OUTPUT" + - name: Check license headers env: # Pull requests check only the files they change; pushes and manual runs check every file. SINCE: ${{ github.event_name == 'pull_request' && format('origin/{0}', github.base_ref) || '' }} run: | mkdir -p target/license-provenance - # A restored cache carries the marker of the run that saved it; only this run's additions may set it. - rm -f target/license-headers-cache/.updated # The runner does nothing else: use every CPU, not all but one as on a workstation. LICENSE_HEADERS_JOBS="$(nproc)" export LICENSE_HEADERS_JOBS @@ -75,11 +80,12 @@ jobs: export LICENSE_HEADERS_CACHE_SIGNATURES=1 ./check-license-headers.sh ${SINCE:+--since "$SINCE"} 2>&1 | tee target/license-provenance/console.log - # Saved even when the check finds problems, but only when the run normalized something the cache lacked. + # Saved even when the check finds problems, but only when the run changed the cache: it normalized something + # the cache lacked, or it pruned the databases of other signatures. - name: Save normalized CE contents if: >- always() && github.event_name != 'pull_request' - && hashFiles('target/license-headers-cache/.updated') != '' + && hashFiles('target/license-headers-cache/*.sqlite') != steps.cache-fingerprint.outputs.hash uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: target/license-headers-cache diff --git a/tools/src/main/python/license-headers/README.md b/tools/src/main/python/license-headers/README.md index efe877b050..6e2b20939e 100644 --- a/tools/src/main/python/license-headers/README.md +++ b/tools/src/main/python/license-headers/README.md @@ -56,7 +56,8 @@ another run holds its lock, the run continues without it. In GitHub Actions, pushes and manual runs save the cache and pull requests only read it: a pull request takes the cache of its base branch, then of `master`. -CI keeps only the current signature, so the saved cache holds one database. +CI keeps only the current signature, so the saved cache holds one database, and +saves it only when the run changed it. ## Check only changed files diff --git a/tools/src/main/python/license-headers/check_license_headers.py b/tools/src/main/python/license-headers/check_license_headers.py index 9010e252d1..11c3e1aa57 100644 --- a/tools/src/main/python/license-headers/check_license_headers.py +++ b/tools/src/main/python/license-headers/check_license_headers.py @@ -74,7 +74,6 @@ JOBS_VARIABLE = "LICENSE_HEADERS_JOBS" CACHE_SIGNATURES_VARIABLE = "LICENSE_HEADERS_CACHE_SIGNATURES" CACHE_DIRECTORY = "target/license-headers-cache" CACHE_FORMAT = "1" -CACHE_UPDATED = ".updated" CACHE_SIGNATURES_KEPT = 3 CACHE_FILE = re.compile(r"[0-9a-f]{32}\.sqlite") # Git's minimum similarity for a copy, in percent: the -C threshold and the size filter in front of it. @@ -937,7 +936,6 @@ class NormalizationCache: self.database = None self.unavailable = None directory.mkdir(parents=True, exist_ok=True) - (directory / CACHE_UPDATED).unlink(missing_ok=True) self.path = directory / f"{signature}.sqlite" try: try: @@ -1020,8 +1018,6 @@ class NormalizationCache: if self.database is not None: self.database.close() self.database = None - if self.added: - (self.directory / CACHE_UPDATED).touch() if self.unavailable: console.line(f"The cache in {self.directory} was unavailable ({self.unavailable}); " "the run continued without it", "dim") @@ -1118,9 +1114,10 @@ def compare(repo, plugin, lineage, contents, cache, in_scope): if mycila.contents[("head", name)].strip()} normalized = head_hashes | {key: comparison_hash(content) for key, content in copy_sources.items()} copies, searched = copy_candidates(repo, plugin, cache, sources, versions, slots, bytes_by_id, - destinations, copy_sources, normalized) + destinations, copy_sources) + normalized |= searched merges = clean_merges(repo, plugin, cache, lineage, names, normalized) - console.end(f"done ({len(normalized)} file versions, {searched} of {len(sources) - len(versions)} " + console.end(f"done ({len(normalized)} file versions, {len(searched)} of {len(sources) - len(versions)} " f"other CE files searched for copies, {cache.hits} from the cache)") return Comparison( lineage=lineage, @@ -1134,16 +1131,16 @@ def compare(repo, plugin, lineage, contents, cache, in_scope): ) -def copy_candidates(repo, plugin, cache, sources, versions, slots, bytes_by_id, destinations, copy_sources, - normalized): - """CE files similar to the paths that CE does not have, normalized only when Git could match them by size.""" +def copy_candidates(repo, plugin, cache, sources, versions, slots, bytes_by_id, destinations, copy_sources): + """CE files similar to the paths that CE does not have, normalized only when Git could match them by size, and + the comparison hashes of the other CE files searched for them.""" if not destinations: - return {}, 0 + return {}, {} sizes = [staged_size(content) for content in destinations.values()] others = sorted(key for key in sources if key not in versions and could_shrink_to_copy(len(bytes_by_id[key[1]]), sizes)) found = normalize(repo, plugin, cache, {key: bytes_by_id[key[1]] for key in others}) - normalized |= {key: comparison_hash(content) for key, content in found.items()} + searched = {key: comparison_hash(content) for key, content in found.items()} with tempfile.TemporaryDirectory(prefix="license-provenance-") as temporary: staging = Mycila(repo, Path(temporary), plugin) for key, content in (found | copy_sources).items(): @@ -1152,7 +1149,7 @@ def copy_candidates(repo, plugin, cache, sources, versions, slots, bytes_by_id, staging.add(("head", name), name, content, slots[("head", name)]) reachable = {key: sources[key] for key in [*others, *copy_sources] if could_be_copy(staged_size(staging.contents[key]), sizes)} - return normalized_copies(staging, reachable, set(destinations), staging.nonempty()), len(others) + return normalized_copies(staging, reachable, set(destinations), staging.nonempty()), searched def clean_merges(repo, plugin, cache, lineage, names, normalized): diff --git a/tools/src/main/python/license-headers/test_check_license_headers.py b/tools/src/main/python/license-headers/test_check_license_headers.py index c1e5bbe2bb..5cd9d1b311 100644 --- a/tools/src/main/python/license-headers/test_check_license_headers.py +++ b/tools/src/main/python/license-headers/test_check_license_headers.py @@ -1296,12 +1296,14 @@ class CacheTests(unittest.TestCase): def test_a_second_run_takes_ce_inputs_from_the_cache_and_reports_the_same(self): first, second = [], [] _, cold, _ = self.check(normalizer=self.normalizer(first)) - self.assertTrue((self.cache() / p.CACHE_UPDATED).exists()) + databases = {path.name: path.read_bytes() for path in self.cache().glob("*.sqlite")} _, warm, output = self.check(normalizer=self.normalizer(second)) self.assertEqual(cold, warm) self.assertTrue(any(key[0] != "head" for batch in first for key in batch)) self.assertEqual({"head"}, {key[0] for batch in second for key in batch}) - self.assertFalse((self.cache() / p.CACHE_UPDATED).exists()) + # CI saves the cache only when its bytes changed: a run that only reads it must leave them as they were. + self.assertTrue(databases) + self.assertEqual(databases, {path.name: path.read_bytes() for path in self.cache().glob("*.sqlite")}) self.assertRegex(output, r"[1-9][0-9]* from the cache") def test_without_the_cache_nothing_is_read_or_written(self): @@ -1338,20 +1340,17 @@ class CacheTests(unittest.TestCase): (repo / p.TEMPLATES["apache"]).write_text("reworded\n") self.assertNotEqual(signature, p.cache_signature(repo, fixture_plugin("1"))) - def test_only_recent_signatures_are_kept_and_the_update_mark_is_fresh(self): + def test_only_recent_signatures_are_kept(self): directory = temporary_directory(self) for index in range(p.CACHE_SIGNATURES_KEPT + 2): stale = directory / f"{signature(f'old{index}')}.sqlite" stale.write_bytes(b"") os.utime(stale, (index, index)) - (directory / p.CACHE_UPDATED).touch() cache = p.NormalizationCache(directory, signature("current")) - self.assertFalse((directory / p.CACHE_UPDATED).exists()) kept = sorted(path.name for path in directory.glob("*.sqlite")) self.assertEqual(p.CACHE_SIGNATURES_KEPT, len(kept)) self.assertIn(f"{signature('current')}.sqlite", kept) cache.close() - self.assertFalse((directory / p.CACHE_UPDATED).exists()) def test_a_damaged_cache_is_started_again(self): directory = temporary_directory(self) @@ -1443,7 +1442,7 @@ class CacheTests(unittest.TestCase): with redirect_stderr(output): cache.close() self.assertIn("continued without it", output.getvalue()) - self.assertFalse((directory / p.CACHE_UPDATED).exists()) + self.assertEqual(0, cache.added) finally: other.rollback() other.close() From 658cdff7a4cfef33ce7ba71b75e11925b2487b59 Mon Sep 17 00:00:00 2001 From: Vladyslav Prykhodko Date: Fri, 13 Nov 2026 01:16:06 +0200 Subject: [PATCH 16/21] Copy search: a probe checks the size filter against the installed Git; --since stages copy sources as a full run does - size_filter_holds runs the real copy search (normalized_copies) on a source of exactly COPY_SIMILARITY % of a destination and on one byte less, and compares Git's answers with could_be_copy. When they disagree the size filter is off for the run: every CE file is searched, the console says so and the report has copySearch.sizeFilter false (null when nothing was searched for copies). It runs only when there are new paths. - Copy sources are staged under zero-padded ranks in key order. Slot numbers used to start after the checked files and sort as strings, so among equally similar CE sources --since and a full run could report different copy candidates. --- .../license-headers/check_license_headers.py | 68 ++++++++++-- .../test_check_license_headers.py | 104 +++++++++++++++++- 2 files changed, 154 insertions(+), 18 deletions(-) diff --git a/tools/src/main/python/license-headers/check_license_headers.py b/tools/src/main/python/license-headers/check_license_headers.py index 11c3e1aa57..a01d776e43 100644 --- a/tools/src/main/python/license-headers/check_license_headers.py +++ b/tools/src/main/python/license-headers/check_license_headers.py @@ -903,6 +903,7 @@ class Comparison: copies: dict merges: dict ce_directories: frozenset + size_filter: bool | None = None def classify(self, name, curation): key = ("head", name) @@ -1073,6 +1074,34 @@ def could_be_copy(size, destinations): return any(100 * min(size, other) >= COPY_SIMILARITY * max(size, other) for other in destinations) +def git_finds_copy(repo, plugin, source, destination): + """Whether the copy search, normalized_copies itself, matches destination, a new path, to source, a CE file.""" + with tempfile.TemporaryDirectory(prefix="license-provenance-") as temporary: + staging = Mycila(repo, Path(temporary), plugin) + staging.add(("Source.java", "probe"), "Source.java", source) + staging.add(("head", "Destination.java"), "Destination.java", destination) + found = normalized_copies(staging, {("Source.java", "probe"): "probe"}, {"Destination.java"}, staging.nonempty()) + return "Destination.java" in found + + +def size_filter_holds(repo, plugin): + """Whether the installed Git still never matches a source that could_be_copy rules out. The filter relies on Git + measuring similarity against the larger blob (estimate_similarity divides by the larger size, and diffcore-delta.c + counts at most the smaller blob as copied), so a source below COPY_SIMILARITY % of a destination can never reach + the threshold. The probe asks the real copy search twice: a source of exactly COPY_SIMILARITY % of a destination + must be found, the same source one byte shorter must not. That catches a Git that measures against anything but + the larger blob; nothing else in this repository would notice such a change, and the filter would then drop CE + files Git matches. Both answers are compared with could_be_copy itself, so a change of the Python rule that no + longer matches Git turns the filter off as well. Each case runs in its own repository, so a found boundary pair + cannot hide the other answer.""" + destination = b"".join(b"line %05d\n" % index for index in range(100)) + boundary = destination[:len(destination) * COPY_SIMILARITY // 100] + sources = [boundary, boundary[:-1]] + rule = [could_be_copy(len(source), [len(destination)]) for source in sources] + answers = parallel(lambda source: git_finds_copy(repo, plugin, source, destination), sources) + return rule == answers == [True, False] + + def could_shrink_to_copy(raw_size, destinations): """Normalizing never grows a file: below COPY_SIMILARITY % of the smallest destination it stays out of Git's reach.""" return 100 * raw_size >= COPY_SIMILARITY * min(destinations) @@ -1093,10 +1122,10 @@ def compare(repo, plugin, lineage, contents, cache, in_scope): for key in comparable_ce_files(files, copy_source_types).items(): sources.setdefault(key, base) versions = {(name, oid) for name in names for _, oid in lineage.versions(name)} - # Every input keeps the slot it has among all inputs, so the copy search sees the same paths, and Git breaks - # ties between equally similar sources the same way, however many sources the size filter drops. - slots = {("head", name): index for index, name in enumerate(names)} - slots |= {key: len(names) + index for index, key in enumerate(sorted(sources))} + # Git breaks ties between equally similar copy sources by path. Sources are staged in key order, padded so that + # paths sort like ranks: --since, a full run and the size filter all present any two sources in the same order. + slots = {("head", name): f"{index:08d}" for index, name in enumerate(sorted(names))} + slots |= {key: f"{index:08d}" for index, key in enumerate(sorted(sources))} bytes_by_id = blobs(repo, [oid for _, oid in sources]) with tempfile.TemporaryDirectory(prefix="license-provenance-") as temporary: mycila = Mycila(repo, Path(temporary), plugin) @@ -1113,8 +1142,8 @@ def compare(repo, plugin, lineage, contents, cache, in_scope): destinations = {name: mycila.contents[("head", name)] for name in sorted(new_paths) if mycila.contents[("head", name)].strip()} normalized = head_hashes | {key: comparison_hash(content) for key, content in copy_sources.items()} - copies, searched = copy_candidates(repo, plugin, cache, sources, versions, slots, bytes_by_id, - destinations, copy_sources) + copies, searched, size_filter = copy_candidates(repo, plugin, cache, sources, versions, slots, bytes_by_id, + destinations, copy_sources) normalized |= searched merges = clean_merges(repo, plugin, cache, lineage, names, normalized) console.end(f"done ({len(normalized)} file versions, {len(searched)} of {len(sources) - len(versions)} " @@ -1128,17 +1157,21 @@ def compare(repo, plugin, lineage, contents, cache, in_scope): merges=merges, ce_directories=frozenset(str(parent) for files in lineage.trees.values() for path in files for parent in PurePosixPath(path).parents), + size_filter=size_filter, ) def copy_candidates(repo, plugin, cache, sources, versions, slots, bytes_by_id, destinations, copy_sources): - """CE files similar to the paths that CE does not have, normalized only when Git could match them by size, and - the comparison hashes of the other CE files searched for them.""" + """CE files similar to the paths that CE does not have, normalized only when Git could match them by size; the + comparison hashes of the other CE files searched for them; and whether the size filter was used, None when there + was nothing to search for.""" if not destinations: - return {}, {} + return {}, {}, None sizes = [staged_size(content) for content in destinations.values()] + # Slower, never wrong: when the installed Git disagrees with the size rule, every CE file is searched. + size_filter = size_filter_holds(repo, plugin) others = sorted(key for key in sources if key not in versions - and could_shrink_to_copy(len(bytes_by_id[key[1]]), sizes)) + and (not size_filter or could_shrink_to_copy(len(bytes_by_id[key[1]]), sizes))) found = normalize(repo, plugin, cache, {key: bytes_by_id[key[1]] for key in others}) searched = {key: comparison_hash(content) for key, content in found.items()} with tempfile.TemporaryDirectory(prefix="license-provenance-") as temporary: @@ -1148,8 +1181,8 @@ def copy_candidates(repo, plugin, cache, sources, versions, slots, bytes_by_id, for name, content in destinations.items(): staging.add(("head", name), name, content, slots[("head", name)]) reachable = {key: sources[key] for key in [*others, *copy_sources] - if could_be_copy(staged_size(staging.contents[key]), sizes)} - return normalized_copies(staging, reachable, set(destinations), staging.nonempty()), searched + if not size_filter or could_be_copy(staged_size(staging.contents[key]), sizes)} + return normalized_copies(staging, reachable, set(destinations), staging.nonempty()), searched, size_filter def clean_merges(repo, plugin, cache, lineage, names, normalized): @@ -1268,6 +1301,10 @@ def select_changes(repo, since, bases, ce_bases, plugin, curations): return Selection(since, base, paths, f"{len(paths)} changed paths") +def git_version(): + return run(["git", "--version"], Path.cwd()).stdout.decode().strip().removeprefix("git version ") + + def current_branch(repo): branch = git(repo, "rev-parse", "--abbrev-ref", "HEAD").decode().strip() return "" if branch == "HEAD" else branch @@ -1523,6 +1560,7 @@ def check(args): console.line(f"Checking {len(checked)} of {len(scope.eligible)} files in scope", "dim") contents = {name: (repo / name).read_bytes() for name in checked} rows = [] + size_filter = None if contents: cache = (NoCache() if args.no_cache else NormalizationCache((repo / args.cache).resolve(), cache_signature(repo, plugin))) @@ -1531,7 +1569,12 @@ def check(args): finally: cache.close() rows = [comparison.classify(name, curations.get(name)) for name in checked] + size_filter = comparison.size_filter console.line() + if size_filter is False: + console.line(f"Git's copy detection (git {git_version()}) and the size rule of the copy search disagree; " + "every CE file was searched for copies. Report this to the maintainers of the check.", "red") + console.line() orphaned = [{"path": name, "status": "stale-curation", "reason": "file is no longer in scope"} for name in sorted(set(curations) - set(scope.eligible))] ensure_inputs_unchanged(repo, lineage, curation_path, curation_bytes, contents) @@ -1547,6 +1590,7 @@ def check(args): "ce": ce | {"bases": list(lineage.bases)}, "scope": {"supported": len(scope.eligible), "unknown": scope.unknown, "modules": scope.modules}, "selection": selection.report() if selection is not None else None, + "copySearch": {"sizeFilter": size_filter}, "summary": dict(summary), "restamped": sorted(row["path"] for row in rows if "previousHeader" in row), "removedCurations": removed, diff --git a/tools/src/main/python/license-headers/test_check_license_headers.py b/tools/src/main/python/license-headers/test_check_license_headers.py index 5cd9d1b311..9989f5b2ec 100644 --- a/tools/src/main/python/license-headers/test_check_license_headers.py +++ b/tools/src/main/python/license-headers/test_check_license_headers.py @@ -1237,8 +1237,8 @@ class CopySearchTests(unittest.TestCase): for category, name in p.TEMPLATES.items(): git.write(name, f"fixture {category}\n") git.write(p.CURATIONS, '{"schemaVersion": 1, "curations": []}') - # Sorted CE sources: a/ (small), b/Alpha, c/ (small), e/Gamma. Among all inputs Gamma takes slot 12 and - # Alpha slot 3, so Gamma comes first in the copy search and wins the tie between the identical sources. + # Sorted CE sources: a/ (small), b/Alpha, c/ (small), e/Gamma. Alpha and Gamma are identical: Alpha ranks first + # among all CE files and wins the tie, whichever sources the size filter drops and whatever else is checked. for name in ("a/Small0.java", "a/Small1.java", *(f"c/Small{index}.java" for index in range(2, 10))): git.write(name, fixture("apache") + "x\n") git.write("b/Alpha.java", fixture("apache") + self.BODY) @@ -1251,16 +1251,108 @@ class CopySearchTests(unittest.TestCase): def test_size_filter_keeps_the_copy_search_result(self): _, filtered, output = self.check() - with (patch.object(p, "could_shrink_to_copy", return_value=True), - patch.object(p, "could_be_copy", return_value=True)): + with patch.object(p, "size_filter_holds", return_value=False): _, unfiltered, unfiltered_output = self.check() - self.assertEqual(unfiltered, filtered) + self.assertEqual(unfiltered["files"], filtered["files"]) + self.assertEqual(({"sizeFilter": True}, {"sizeFilter": False}), + (filtered["copySearch"], unfiltered["copySearch"])) + self.assertNotIn("and the size rule of the copy search disagree", output) + self.assertIn("and the size rule of the copy search disagree", unfiltered_output) row = self.rows(filtered)["d/Delta.java"] self.assertEqual(("unresolved", "apache"), (row["status"], row["suggestedHeader"])) - self.assertEqual(["e/Gamma.java"], [copy["path"] for copy in row["copyCandidates"]]) + self.assertEqual(["b/Alpha.java"], [copy["path"] for copy in row["copyCandidates"]]) self.assertIn("2 of 12 other CE files searched for copies", output) self.assertIn("12 of 12 other CE files searched for copies", unfiltered_output) + def test_since_reports_the_copy_a_full_run_reports_among_equally_similar_sources(self): + # TB files beside the new one shift where the checked inputs sit among all inputs of a full run. + others = [f"t/Tb{index}.java" for index in range(7)] + self.git("reset", "-q", "--hard", "HEAD~1") + for name in others: + self.git.write(name, fixture(p.NON_CE) + f"TB source {name}\n") + self.relicensing = self.git.commit("relicensing with TB files") + self.git("checkout", "-q", "-b", "feature") + self.git.write("d/Delta.java", fixture(p.NON_CE) + self.BODY) + self.git.commit("copy of a CE file under a new path") + scope = sorted(others + ["d/Delta.java"]) + _, full, _ = self.check(scope=scope) + _, since, _ = self.check("--since", "master", scope=scope) + self.assertEqual(["d/Delta.java"], [row["path"] for row in since["files"]]) + row = self.rows(full)["d/Delta.java"] + self.assertEqual(("unresolved", 1), (row["status"], len(row["copyCandidates"]))) + self.assertEqual("b/Alpha.java", row["copyCandidates"][0]["path"]) + self.assertEqual(row, self.rows(since)["d/Delta.java"]) + + def test_without_the_size_filter_git_searches_every_ce_file(self): + searched = [] + copies = p.normalized_copies + + def spy(mycila, source_refs, names, nonempty): + if "d/Delta.java" in names: # not the size probe + searched.append(sorted(key[0] for key in source_refs)) + return copies(mycila, source_refs, names, nonempty) + + with patch.object(p, "normalized_copies", spy): + self.check() + with patch.object(p, "size_filter_holds", return_value=False): + self.check() + filtered, unfiltered = searched + self.assertEqual(["b/Alpha.java", "e/Gamma.java"], filtered) + self.assertEqual(12, len(unfiltered)) + + def probe(self): + return p.size_filter_holds(this_repository(), fixture_plugin()) + + def test_size_filter_holds_for_the_installed_git(self): + self.assertTrue(self.probe()) + + def test_a_python_rule_that_no_longer_matches_git_turns_the_size_filter_off(self): + stricter = lambda size, destinations: any(100 * min(size, other) > p.COPY_SIMILARITY * max(size, other) + for other in destinations) + with patch.object(p, "could_be_copy", stricter): + self.assertFalse(self.probe()) + + def test_report_marks_the_size_filter_only_when_copies_were_searched(self): + _, report, _ = self.check() + self.assertEqual({"sizeFilter": True}, report["copySearch"]) + self.git.write("d/Delta.java", fixture("apache") + "base implementation\n") + self.git.commit("Delta in CE as well") + with patch.object(p, "RELICENSING_COMMIT", "0" * 40), patch.object(p, "relicensed_ce_bases", + return_value=[self.git("rev-parse", "HEAD")]): + _, report, output = self.check() + self.assertEqual({"sizeFilter": None}, report["copySearch"]) + self.assertNotIn("and the size rule of the copy search disagree", output) + + def test_size_filter_is_off_when_git_answers_otherwise_on_either_side_of_the_boundary(self): + boundary = 1000 * p.COPY_SIMILARITY // 100 + 100 * p.COPY_SIMILARITY // 100 # 100 lines of 11 bytes + + def git(at_boundary, below): + return lambda repo, plugin, source, destination: at_boundary if len(source) == boundary else below + + for at_boundary, below, holds in ((True, False, True), # Git follows the rule + (True, True, False), # looser: a CE file below the boundary matches + (False, False, False), # the boundary pair does not match either + (False, True, False)): + with patch.object(p, "git_finds_copy", git(at_boundary, below)): + self.assertEqual(holds, self.probe(), (at_boundary, below)) + + def test_probe_pairs_sit_on_both_sides_of_the_boundary(self): + sizes = [] + def finds(repo, plugin, source, destination): + sizes.append((len(source), len(destination))) + return len(source) % 2 == 0 + + with patch.dict(os.environ, {p.JOBS_VARIABLE: "1"}), patch.object(p, "git_finds_copy", finds): + self.assertTrue(self.probe()) + (boundary, destination), (below, _) = sizes + self.assertEqual((boundary * 100, below), (p.COPY_SIMILARITY * destination, boundary - 1)) + + def test_size_filter_follows_the_configured_similarity(self): + with patch.object(p, "COPY_SIMILARITY", 60): + self.assertTrue(self.probe()) + self.assertTrue(p.could_be_copy(600, [1000])) + self.assertFalse(p.could_be_copy(599, [1000])) + def test_a_file_grown_by_normalizing_fails_the_check(self): def strip_headers(tool): tool.removed, tool.stacked = {key: b"" for key in tool.contents}, set() From ae46a3631c93830003e62c5fe825d4ac3e2f0461 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Fri, 13 Nov 2026 10:54:28 +0200 Subject: [PATCH 17/21] Version set to 4.2.2.9-SNAPSHOT --- application/pom.xml | 2 +- common/actor/pom.xml | 2 +- common/cache/pom.xml | 2 +- common/cluster-api/pom.xml | 2 +- common/coap-server/pom.xml | 2 +- common/dao-api/pom.xml | 2 +- common/data/pom.xml | 2 +- common/discovery-api/pom.xml | 2 +- common/edge-api/pom.xml | 2 +- common/edge-api/src/main/proto/edge.proto | 1 + common/edqs/pom.xml | 2 +- common/message/pom.xml | 2 +- common/pom.xml | 2 +- common/proto/pom.xml | 2 +- common/queue/pom.xml | 2 +- common/script/pom.xml | 2 +- common/script/remote-js-client/pom.xml | 2 +- common/script/script-api/pom.xml | 2 +- common/stats/pom.xml | 2 +- common/transport/coap/pom.xml | 2 +- common/transport/http/pom.xml | 2 +- common/transport/lwm2m/pom.xml | 2 +- common/transport/mqtt/pom.xml | 2 +- common/transport/pom.xml | 2 +- common/transport/snmp/pom.xml | 2 +- common/transport/transport-api/pom.xml | 2 +- common/util/pom.xml | 2 +- common/version-control/pom.xml | 2 +- dao/pom.xml | 2 +- edqs/pom.xml | 2 +- monitoring/pom.xml | 2 +- msa/black-box-tests/pom.xml | 2 +- msa/edqs/pom.xml | 2 +- msa/js-executor/package.json | 2 +- msa/js-executor/pom.xml | 2 +- msa/monitoring/pom.xml | 2 +- msa/pom.xml | 2 +- msa/tb-node/pom.xml | 2 +- msa/tb/pom.xml | 2 +- msa/transport/coap/pom.xml | 2 +- msa/transport/http/pom.xml | 2 +- msa/transport/lwm2m/pom.xml | 2 +- msa/transport/mqtt/pom.xml | 2 +- msa/transport/pom.xml | 2 +- msa/transport/snmp/pom.xml | 2 +- msa/vc-executor-docker/pom.xml | 2 +- msa/vc-executor/pom.xml | 2 +- msa/web-ui/package.json | 2 +- msa/web-ui/pom.xml | 2 +- netty-mqtt/pom.xml | 4 ++-- pom.xml | 2 +- rest-client/pom.xml | 2 +- rule-engine/pom.xml | 2 +- rule-engine/rule-engine-api/pom.xml | 2 +- rule-engine/rule-engine-components/pom.xml | 2 +- tools/pom.xml | 2 +- transport/coap/pom.xml | 2 +- transport/http/pom.xml | 2 +- transport/lwm2m/pom.xml | 2 +- transport/mqtt/pom.xml | 2 +- transport/pom.xml | 2 +- transport/snmp/pom.xml | 2 +- ui-ngx/package.json | 2 +- ui-ngx/pom.xml | 2 +- 64 files changed, 65 insertions(+), 64 deletions(-) diff --git a/application/pom.xml b/application/pom.xml index 59bc549af1..d843ca393f 100644 --- a/application/pom.xml +++ b/application/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT thingsboard application diff --git a/common/actor/pom.xml b/common/actor/pom.xml index 808dfab5d1..8fecf54ad6 100644 --- a/common/actor/pom.xml +++ b/common/actor/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT common org.thingsboard.common diff --git a/common/cache/pom.xml b/common/cache/pom.xml index 2cf6bd7d2d..5c6273d161 100644 --- a/common/cache/pom.xml +++ b/common/cache/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT common org.thingsboard.common diff --git a/common/cluster-api/pom.xml b/common/cluster-api/pom.xml index d3acfc7d3a..e49977a01c 100644 --- a/common/cluster-api/pom.xml +++ b/common/cluster-api/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT common org.thingsboard.common diff --git a/common/coap-server/pom.xml b/common/coap-server/pom.xml index 57ed51925e..7637abe3c0 100644 --- a/common/coap-server/pom.xml +++ b/common/coap-server/pom.xml @@ -11,7 +11,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT common org.thingsboard.common diff --git a/common/dao-api/pom.xml b/common/dao-api/pom.xml index 1c7e2716c1..c49a4cab04 100644 --- a/common/dao-api/pom.xml +++ b/common/dao-api/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT common org.thingsboard.common diff --git a/common/data/pom.xml b/common/data/pom.xml index 2800181cce..084a5ffd06 100644 --- a/common/data/pom.xml +++ b/common/data/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT common org.thingsboard.common diff --git a/common/discovery-api/pom.xml b/common/discovery-api/pom.xml index 18409e9e7f..dfcaa1c892 100644 --- a/common/discovery-api/pom.xml +++ b/common/discovery-api/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT common org.thingsboard.common diff --git a/common/edge-api/pom.xml b/common/edge-api/pom.xml index 649a568e63..f830649a9f 100644 --- a/common/edge-api/pom.xml +++ b/common/edge-api/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT common org.thingsboard.common diff --git a/common/edge-api/src/main/proto/edge.proto b/common/edge-api/src/main/proto/edge.proto index 9eb00490ab..5e2f2cec10 100644 --- a/common/edge-api/src/main/proto/edge.proto +++ b/common/edge-api/src/main/proto/edge.proto @@ -41,6 +41,7 @@ enum EdgeVersion { V_4_2_2_6 = 4226; V_4_2_2_7 = 4227; V_4_2_2_8 = 4228; + V_4_2_2_9 = 4229; V_LATEST = 99999; } diff --git a/common/edqs/pom.xml b/common/edqs/pom.xml index ab2a7739b9..c61eb3fc2b 100644 --- a/common/edqs/pom.xml +++ b/common/edqs/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT common org.thingsboard.common diff --git a/common/message/pom.xml b/common/message/pom.xml index 779d03f413..ce8b01649c 100644 --- a/common/message/pom.xml +++ b/common/message/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT common org.thingsboard.common diff --git a/common/pom.xml b/common/pom.xml index baeac2355d..857cbc8b30 100644 --- a/common/pom.xml +++ b/common/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT thingsboard common diff --git a/common/proto/pom.xml b/common/proto/pom.xml index c6ebedaf0d..cfc451d7a2 100644 --- a/common/proto/pom.xml +++ b/common/proto/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT common org.thingsboard.common diff --git a/common/queue/pom.xml b/common/queue/pom.xml index 33a07c68f4..717c0f418a 100644 --- a/common/queue/pom.xml +++ b/common/queue/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT common org.thingsboard.common diff --git a/common/script/pom.xml b/common/script/pom.xml index 67f973a213..666da9adb8 100644 --- a/common/script/pom.xml +++ b/common/script/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT common org.thingsboard.common diff --git a/common/script/remote-js-client/pom.xml b/common/script/remote-js-client/pom.xml index 2745b2494e..ed1054361c 100644 --- a/common/script/remote-js-client/pom.xml +++ b/common/script/remote-js-client/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT script org.thingsboard.common.script diff --git a/common/script/script-api/pom.xml b/common/script/script-api/pom.xml index ac3a2c8ce0..3a9466dc9c 100644 --- a/common/script/script-api/pom.xml +++ b/common/script/script-api/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT script org.thingsboard.common.script diff --git a/common/stats/pom.xml b/common/stats/pom.xml index 1ca785c74b..2abc42e4ba 100644 --- a/common/stats/pom.xml +++ b/common/stats/pom.xml @@ -11,7 +11,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT common org.thingsboard.common diff --git a/common/transport/coap/pom.xml b/common/transport/coap/pom.xml index 99e5352a6e..f2bd149768 100644 --- a/common/transport/coap/pom.xml +++ b/common/transport/coap/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT transport org.thingsboard.common.transport diff --git a/common/transport/http/pom.xml b/common/transport/http/pom.xml index 789dea2438..d96b894651 100644 --- a/common/transport/http/pom.xml +++ b/common/transport/http/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT transport org.thingsboard.common.transport diff --git a/common/transport/lwm2m/pom.xml b/common/transport/lwm2m/pom.xml index a928c2a1b8..57835189bf 100644 --- a/common/transport/lwm2m/pom.xml +++ b/common/transport/lwm2m/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT transport org.thingsboard.common.transport diff --git a/common/transport/mqtt/pom.xml b/common/transport/mqtt/pom.xml index 4137ca9796..e0b653d722 100644 --- a/common/transport/mqtt/pom.xml +++ b/common/transport/mqtt/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT transport org.thingsboard.common.transport diff --git a/common/transport/pom.xml b/common/transport/pom.xml index 5bb3d0ce21..a5ce23abda 100644 --- a/common/transport/pom.xml +++ b/common/transport/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT common org.thingsboard.common diff --git a/common/transport/snmp/pom.xml b/common/transport/snmp/pom.xml index 9f985b4182..c2b9941975 100644 --- a/common/transport/snmp/pom.xml +++ b/common/transport/snmp/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.common - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT transport diff --git a/common/transport/transport-api/pom.xml b/common/transport/transport-api/pom.xml index b7a914c344..5d85c26ae9 100644 --- a/common/transport/transport-api/pom.xml +++ b/common/transport/transport-api/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT transport org.thingsboard.common.transport diff --git a/common/util/pom.xml b/common/util/pom.xml index 74d62be1f5..bab63fdb68 100644 --- a/common/util/pom.xml +++ b/common/util/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT common org.thingsboard.common diff --git a/common/version-control/pom.xml b/common/version-control/pom.xml index 61241550a5..bd1ac80027 100644 --- a/common/version-control/pom.xml +++ b/common/version-control/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT common org.thingsboard.common diff --git a/dao/pom.xml b/dao/pom.xml index af8bc35424..baa5e75abb 100644 --- a/dao/pom.xml +++ b/dao/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT thingsboard dao diff --git a/edqs/pom.xml b/edqs/pom.xml index c0f241042d..32b190a032 100644 --- a/edqs/pom.xml +++ b/edqs/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT thingsboard edqs diff --git a/monitoring/pom.xml b/monitoring/pom.xml index a88c0fc8c4..bc9be08511 100644 --- a/monitoring/pom.xml +++ b/monitoring/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT thingsboard diff --git a/msa/black-box-tests/pom.xml b/msa/black-box-tests/pom.xml index 818fb4539c..fce897bcff 100644 --- a/msa/black-box-tests/pom.xml +++ b/msa/black-box-tests/pom.xml @@ -10,7 +10,7 @@ org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/edqs/pom.xml b/msa/edqs/pom.xml index 1576d062e1..3911adb117 100644 --- a/msa/edqs/pom.xml +++ b/msa/edqs/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/js-executor/package.json b/msa/js-executor/package.json index 61b49d854d..d77e6aeb64 100644 --- a/msa/js-executor/package.json +++ b/msa/js-executor/package.json @@ -1,7 +1,7 @@ { "name": "thingsboard-js-executor", "private": true, - "version": "4.2.2.8", + "version": "4.2.2.9", "description": "ThingsBoard JavaScript Executor Microservice", "main": "server.ts", "bin": "server.js", diff --git a/msa/js-executor/pom.xml b/msa/js-executor/pom.xml index acebc9dc51..cf4b4554df 100644 --- a/msa/js-executor/pom.xml +++ b/msa/js-executor/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/monitoring/pom.xml b/msa/monitoring/pom.xml index ae6bb05401..a3217583eb 100644 --- a/msa/monitoring/pom.xml +++ b/msa/monitoring/pom.xml @@ -11,7 +11,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT msa diff --git a/msa/pom.xml b/msa/pom.xml index 346e4b0a19..552c85e9a4 100644 --- a/msa/pom.xml +++ b/msa/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT thingsboard msa diff --git a/msa/tb-node/pom.xml b/msa/tb-node/pom.xml index 5b6294d88b..5e29c4c90a 100644 --- a/msa/tb-node/pom.xml +++ b/msa/tb-node/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/tb/pom.xml b/msa/tb/pom.xml index 920a1055f2..bdc65c8a24 100644 --- a/msa/tb/pom.xml +++ b/msa/tb/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/transport/coap/pom.xml b/msa/transport/coap/pom.xml index 15c09b85f0..7094681e70 100644 --- a/msa/transport/coap/pom.xml +++ b/msa/transport/coap/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.msa - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT transport org.thingsboard.msa.transport diff --git a/msa/transport/http/pom.xml b/msa/transport/http/pom.xml index d8b04667ca..939d28e964 100644 --- a/msa/transport/http/pom.xml +++ b/msa/transport/http/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.msa - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT transport org.thingsboard.msa.transport diff --git a/msa/transport/lwm2m/pom.xml b/msa/transport/lwm2m/pom.xml index 89798003a1..907dc00317 100644 --- a/msa/transport/lwm2m/pom.xml +++ b/msa/transport/lwm2m/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.msa - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT transport org.thingsboard.msa.transport diff --git a/msa/transport/mqtt/pom.xml b/msa/transport/mqtt/pom.xml index 5858b3f8a9..eb4081deaf 100644 --- a/msa/transport/mqtt/pom.xml +++ b/msa/transport/mqtt/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.msa - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT transport org.thingsboard.msa.transport diff --git a/msa/transport/pom.xml b/msa/transport/pom.xml index 30560a4696..9dd7db6c30 100644 --- a/msa/transport/pom.xml +++ b/msa/transport/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/transport/snmp/pom.xml b/msa/transport/snmp/pom.xml index 714e09a8bf..e623402bda 100644 --- a/msa/transport/snmp/pom.xml +++ b/msa/transport/snmp/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa transport - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT org.thingsboard.msa.transport diff --git a/msa/vc-executor-docker/pom.xml b/msa/vc-executor-docker/pom.xml index e36a380931..b800a6b8d0 100644 --- a/msa/vc-executor-docker/pom.xml +++ b/msa/vc-executor-docker/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/vc-executor/pom.xml b/msa/vc-executor/pom.xml index 89665afdee..e6cc39ca5b 100644 --- a/msa/vc-executor/pom.xml +++ b/msa/vc-executor/pom.xml @@ -10,7 +10,7 @@ org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/web-ui/package.json b/msa/web-ui/package.json index 7ea7bbef68..b29f93d68c 100644 --- a/msa/web-ui/package.json +++ b/msa/web-ui/package.json @@ -1,7 +1,7 @@ { "name": "thingsboard-web-ui", "private": true, - "version": "4.2.2.8", + "version": "4.2.2.9", "description": "ThingsBoard Web UI Microservice", "main": "server.ts", "bin": "server.js", diff --git a/msa/web-ui/pom.xml b/msa/web-ui/pom.xml index 09028dc901..1e9093e8f1 100644 --- a/msa/web-ui/pom.xml +++ b/msa/web-ui/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT msa org.thingsboard.msa diff --git a/netty-mqtt/pom.xml b/netty-mqtt/pom.xml index bee910e06f..9958535d5e 100644 --- a/netty-mqtt/pom.xml +++ b/netty-mqtt/pom.xml @@ -8,11 +8,11 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT thingsboard netty-mqtt - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT jar Netty MQTT Client diff --git a/pom.xml b/pom.xml index 23c399bae0..04a56edd4a 100755 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT pom Thingsboard diff --git a/rest-client/pom.xml b/rest-client/pom.xml index 603ac70832..e0b48ebc6e 100644 --- a/rest-client/pom.xml +++ b/rest-client/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT thingsboard rest-client diff --git a/rule-engine/pom.xml b/rule-engine/pom.xml index e4643d15b9..131fd7177d 100644 --- a/rule-engine/pom.xml +++ b/rule-engine/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT thingsboard rule-engine diff --git a/rule-engine/rule-engine-api/pom.xml b/rule-engine/rule-engine-api/pom.xml index 30b58b11f4..d05c6fe473 100644 --- a/rule-engine/rule-engine-api/pom.xml +++ b/rule-engine/rule-engine-api/pom.xml @@ -11,7 +11,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT rule-engine org.thingsboard.rule-engine diff --git a/rule-engine/rule-engine-components/pom.xml b/rule-engine/rule-engine-components/pom.xml index 4268431e93..8246d37aff 100644 --- a/rule-engine/rule-engine-components/pom.xml +++ b/rule-engine/rule-engine-components/pom.xml @@ -11,7 +11,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT rule-engine org.thingsboard.rule-engine diff --git a/tools/pom.xml b/tools/pom.xml index 36807000eb..e14ad4e583 100644 --- a/tools/pom.xml +++ b/tools/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT thingsboard tools diff --git a/transport/coap/pom.xml b/transport/coap/pom.xml index 22e6786113..1e5a00a271 100644 --- a/transport/coap/pom.xml +++ b/transport/coap/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT transport org.thingsboard.transport diff --git a/transport/http/pom.xml b/transport/http/pom.xml index f00a7562ea..fdb9898132 100644 --- a/transport/http/pom.xml +++ b/transport/http/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT transport org.thingsboard.transport diff --git a/transport/lwm2m/pom.xml b/transport/lwm2m/pom.xml index 89eb572a63..77dabb6f85 100644 --- a/transport/lwm2m/pom.xml +++ b/transport/lwm2m/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT transport org.thingsboard.transport diff --git a/transport/mqtt/pom.xml b/transport/mqtt/pom.xml index e944238986..260c1f8e09 100644 --- a/transport/mqtt/pom.xml +++ b/transport/mqtt/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT transport org.thingsboard.transport diff --git a/transport/pom.xml b/transport/pom.xml index 8848af0ce5..12273231ec 100644 --- a/transport/pom.xml +++ b/transport/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT thingsboard transport diff --git a/transport/snmp/pom.xml b/transport/snmp/pom.xml index 73e8b70827..0bd213a786 100644 --- a/transport/snmp/pom.xml +++ b/transport/snmp/pom.xml @@ -10,7 +10,7 @@ org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT transport diff --git a/ui-ngx/package.json b/ui-ngx/package.json index 2c39adf193..be559b93cc 100644 --- a/ui-ngx/package.json +++ b/ui-ngx/package.json @@ -1,6 +1,6 @@ { "name": "thingsboard", - "version": "4.2.2.8", + "version": "4.2.2.9", "scripts": { "ng": "ng", "start": "node --max_old_space_size=8048 ./node_modules/@angular/cli/bin/ng serve --configuration development --host 0.0.0.0 --open", diff --git a/ui-ngx/pom.xml b/ui-ngx/pom.xml index 1052d07b19..d0d5487d9a 100644 --- a/ui-ngx/pom.xml +++ b/ui-ngx/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.2.2.8-SNAPSHOT + 4.2.2.9-SNAPSHOT thingsboard org.thingsboard From 5a2118ff5109c17a55605a8ef9ea0ef8a30a1445 Mon Sep 17 00:00:00 2001 From: Viacheslav Klimov Date: Fri, 13 Nov 2026 10:55:04 +0200 Subject: [PATCH 18/21] Version set to 4.3.1.9-SNAPSHOT --- application/pom.xml | 2 +- common/actor/pom.xml | 2 +- common/cache/pom.xml | 2 +- common/cluster-api/pom.xml | 2 +- common/coap-server/pom.xml | 2 +- common/dao-api/pom.xml | 2 +- common/data/pom.xml | 2 +- common/discovery-api/pom.xml | 2 +- common/edge-api/pom.xml | 2 +- common/edge-api/src/main/proto/edge.proto | 1 + common/edqs/pom.xml | 2 +- common/message/pom.xml | 2 +- common/pom.xml | 2 +- common/proto/pom.xml | 2 +- common/queue/pom.xml | 2 +- common/script/pom.xml | 2 +- common/script/remote-js-client/pom.xml | 2 +- common/script/script-api/pom.xml | 2 +- common/stats/pom.xml | 2 +- common/transport/coap/pom.xml | 2 +- common/transport/http/pom.xml | 2 +- common/transport/lwm2m/pom.xml | 2 +- common/transport/mqtt/pom.xml | 2 +- common/transport/pom.xml | 2 +- common/transport/snmp/pom.xml | 2 +- common/transport/transport-api/pom.xml | 2 +- common/util/pom.xml | 2 +- common/version-control/pom.xml | 2 +- dao/pom.xml | 2 +- edqs/pom.xml | 2 +- monitoring/pom.xml | 2 +- msa/black-box-tests/pom.xml | 2 +- msa/edqs/pom.xml | 2 +- msa/js-executor/package.json | 2 +- msa/js-executor/pom.xml | 2 +- msa/monitoring/pom.xml | 2 +- msa/pom.xml | 2 +- msa/tb-node/pom.xml | 2 +- msa/tb/pom.xml | 2 +- msa/transport/coap/pom.xml | 2 +- msa/transport/http/pom.xml | 2 +- msa/transport/lwm2m/pom.xml | 2 +- msa/transport/mqtt/pom.xml | 2 +- msa/transport/pom.xml | 2 +- msa/transport/snmp/pom.xml | 2 +- msa/vc-executor-docker/pom.xml | 2 +- msa/vc-executor/pom.xml | 2 +- msa/web-ui/package.json | 2 +- msa/web-ui/pom.xml | 2 +- netty-mqtt/pom.xml | 4 ++-- pom.xml | 2 +- rest-client/pom.xml | 2 +- rule-engine/pom.xml | 2 +- rule-engine/rule-engine-api/pom.xml | 2 +- rule-engine/rule-engine-components/pom.xml | 2 +- tools/pom.xml | 2 +- transport/coap/pom.xml | 2 +- transport/http/pom.xml | 2 +- transport/lwm2m/pom.xml | 2 +- transport/mqtt/pom.xml | 2 +- transport/pom.xml | 2 +- transport/snmp/pom.xml | 2 +- ui-ngx/package.json | 2 +- ui-ngx/pom.xml | 2 +- 64 files changed, 65 insertions(+), 64 deletions(-) diff --git a/application/pom.xml b/application/pom.xml index bb4cb6595f..445919a508 100644 --- a/application/pom.xml +++ b/application/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT thingsboard application diff --git a/common/actor/pom.xml b/common/actor/pom.xml index e6e009c943..1c062e8139 100644 --- a/common/actor/pom.xml +++ b/common/actor/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT common org.thingsboard.common diff --git a/common/cache/pom.xml b/common/cache/pom.xml index 122d415dc9..3569bc30b0 100644 --- a/common/cache/pom.xml +++ b/common/cache/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT common org.thingsboard.common diff --git a/common/cluster-api/pom.xml b/common/cluster-api/pom.xml index e0ce47aad4..ca899d3562 100644 --- a/common/cluster-api/pom.xml +++ b/common/cluster-api/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT common org.thingsboard.common diff --git a/common/coap-server/pom.xml b/common/coap-server/pom.xml index f2049b758f..ad96299b4d 100644 --- a/common/coap-server/pom.xml +++ b/common/coap-server/pom.xml @@ -11,7 +11,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT common org.thingsboard.common diff --git a/common/dao-api/pom.xml b/common/dao-api/pom.xml index 7dc02218e3..2e6660abb6 100644 --- a/common/dao-api/pom.xml +++ b/common/dao-api/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT common org.thingsboard.common diff --git a/common/data/pom.xml b/common/data/pom.xml index 26527cf1ef..932f6b92f6 100644 --- a/common/data/pom.xml +++ b/common/data/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT common org.thingsboard.common diff --git a/common/discovery-api/pom.xml b/common/discovery-api/pom.xml index f0e1b776c3..7dba8f7a72 100644 --- a/common/discovery-api/pom.xml +++ b/common/discovery-api/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT common org.thingsboard.common diff --git a/common/edge-api/pom.xml b/common/edge-api/pom.xml index d8aed53d6e..6572180372 100644 --- a/common/edge-api/pom.xml +++ b/common/edge-api/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT common org.thingsboard.common diff --git a/common/edge-api/src/main/proto/edge.proto b/common/edge-api/src/main/proto/edge.proto index 2923d7a682..edf0c865f6 100644 --- a/common/edge-api/src/main/proto/edge.proto +++ b/common/edge-api/src/main/proto/edge.proto @@ -53,6 +53,7 @@ enum EdgeVersion { V_4_3_1_6 = 4316; V_4_3_1_7 = 4317; V_4_3_1_8 = 4318; + V_4_3_1_9 = 4319; V_LATEST = 99999; } diff --git a/common/edqs/pom.xml b/common/edqs/pom.xml index 6107e2b4fe..4c9c01db1d 100644 --- a/common/edqs/pom.xml +++ b/common/edqs/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT common org.thingsboard.common diff --git a/common/message/pom.xml b/common/message/pom.xml index bc63d9aa6a..6a2a641b99 100644 --- a/common/message/pom.xml +++ b/common/message/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT common org.thingsboard.common diff --git a/common/pom.xml b/common/pom.xml index 5476af4de2..22ce4255e2 100644 --- a/common/pom.xml +++ b/common/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT thingsboard common diff --git a/common/proto/pom.xml b/common/proto/pom.xml index ab85c9e1b4..e4e9fbbc52 100644 --- a/common/proto/pom.xml +++ b/common/proto/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT common org.thingsboard.common diff --git a/common/queue/pom.xml b/common/queue/pom.xml index 4ebe75c1e4..fd0d785815 100644 --- a/common/queue/pom.xml +++ b/common/queue/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT common org.thingsboard.common diff --git a/common/script/pom.xml b/common/script/pom.xml index f87736920a..240d10f5a0 100644 --- a/common/script/pom.xml +++ b/common/script/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT common org.thingsboard.common diff --git a/common/script/remote-js-client/pom.xml b/common/script/remote-js-client/pom.xml index f2f993dc00..837ba319b3 100644 --- a/common/script/remote-js-client/pom.xml +++ b/common/script/remote-js-client/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT script org.thingsboard.common.script diff --git a/common/script/script-api/pom.xml b/common/script/script-api/pom.xml index 8c4aed3611..37347f3069 100644 --- a/common/script/script-api/pom.xml +++ b/common/script/script-api/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT script org.thingsboard.common.script diff --git a/common/stats/pom.xml b/common/stats/pom.xml index f898edb95f..37a335a531 100644 --- a/common/stats/pom.xml +++ b/common/stats/pom.xml @@ -11,7 +11,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT common org.thingsboard.common diff --git a/common/transport/coap/pom.xml b/common/transport/coap/pom.xml index 3f3fe4a065..37372cc31f 100644 --- a/common/transport/coap/pom.xml +++ b/common/transport/coap/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT transport org.thingsboard.common.transport diff --git a/common/transport/http/pom.xml b/common/transport/http/pom.xml index c4358412a1..1821510713 100644 --- a/common/transport/http/pom.xml +++ b/common/transport/http/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT transport org.thingsboard.common.transport diff --git a/common/transport/lwm2m/pom.xml b/common/transport/lwm2m/pom.xml index 1795c3d2a0..f0633b7436 100644 --- a/common/transport/lwm2m/pom.xml +++ b/common/transport/lwm2m/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT transport org.thingsboard.common.transport diff --git a/common/transport/mqtt/pom.xml b/common/transport/mqtt/pom.xml index baf8a8ec99..01093c2e76 100644 --- a/common/transport/mqtt/pom.xml +++ b/common/transport/mqtt/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT transport org.thingsboard.common.transport diff --git a/common/transport/pom.xml b/common/transport/pom.xml index 8aac3ac3cd..4711463195 100644 --- a/common/transport/pom.xml +++ b/common/transport/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT common org.thingsboard.common diff --git a/common/transport/snmp/pom.xml b/common/transport/snmp/pom.xml index 13670dff1f..8369e71b0f 100644 --- a/common/transport/snmp/pom.xml +++ b/common/transport/snmp/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.common - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT transport diff --git a/common/transport/transport-api/pom.xml b/common/transport/transport-api/pom.xml index 97be2c8867..bb08508232 100644 --- a/common/transport/transport-api/pom.xml +++ b/common/transport/transport-api/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT transport org.thingsboard.common.transport diff --git a/common/util/pom.xml b/common/util/pom.xml index 3441c8a23f..b1471eff19 100644 --- a/common/util/pom.xml +++ b/common/util/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT common org.thingsboard.common diff --git a/common/version-control/pom.xml b/common/version-control/pom.xml index 22e9bc1ca3..6d080176be 100644 --- a/common/version-control/pom.xml +++ b/common/version-control/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT common org.thingsboard.common diff --git a/dao/pom.xml b/dao/pom.xml index 9d71087d63..e01faf06c5 100644 --- a/dao/pom.xml +++ b/dao/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT thingsboard dao diff --git a/edqs/pom.xml b/edqs/pom.xml index 14e1db87cd..472b2002a8 100644 --- a/edqs/pom.xml +++ b/edqs/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT thingsboard edqs diff --git a/monitoring/pom.xml b/monitoring/pom.xml index 6a59464c16..d86b08196a 100644 --- a/monitoring/pom.xml +++ b/monitoring/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT thingsboard diff --git a/msa/black-box-tests/pom.xml b/msa/black-box-tests/pom.xml index 707dafd8e7..cb6b6525de 100644 --- a/msa/black-box-tests/pom.xml +++ b/msa/black-box-tests/pom.xml @@ -10,7 +10,7 @@ org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/edqs/pom.xml b/msa/edqs/pom.xml index c24c2595e7..376c361ddc 100644 --- a/msa/edqs/pom.xml +++ b/msa/edqs/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/js-executor/package.json b/msa/js-executor/package.json index fc6814a8bf..36f876647d 100644 --- a/msa/js-executor/package.json +++ b/msa/js-executor/package.json @@ -1,7 +1,7 @@ { "name": "thingsboard-js-executor", "private": true, - "version": "4.3.1.8", + "version": "4.3.1.9", "description": "ThingsBoard JavaScript Executor Microservice", "main": "server.ts", "bin": "server.js", diff --git a/msa/js-executor/pom.xml b/msa/js-executor/pom.xml index 7c3adb0233..f4a650e631 100644 --- a/msa/js-executor/pom.xml +++ b/msa/js-executor/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/monitoring/pom.xml b/msa/monitoring/pom.xml index 7903895515..054bf83d6d 100644 --- a/msa/monitoring/pom.xml +++ b/msa/monitoring/pom.xml @@ -11,7 +11,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT msa diff --git a/msa/pom.xml b/msa/pom.xml index 12b4d93a1b..e5f279ad89 100644 --- a/msa/pom.xml +++ b/msa/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT thingsboard msa diff --git a/msa/tb-node/pom.xml b/msa/tb-node/pom.xml index ee64056321..9130b431d6 100644 --- a/msa/tb-node/pom.xml +++ b/msa/tb-node/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/tb/pom.xml b/msa/tb/pom.xml index db709ebcc3..a11a80b371 100644 --- a/msa/tb/pom.xml +++ b/msa/tb/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/transport/coap/pom.xml b/msa/transport/coap/pom.xml index f7170ca978..435598463f 100644 --- a/msa/transport/coap/pom.xml +++ b/msa/transport/coap/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.msa - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT transport org.thingsboard.msa.transport diff --git a/msa/transport/http/pom.xml b/msa/transport/http/pom.xml index 23d46a1c97..19d04294d4 100644 --- a/msa/transport/http/pom.xml +++ b/msa/transport/http/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.msa - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT transport org.thingsboard.msa.transport diff --git a/msa/transport/lwm2m/pom.xml b/msa/transport/lwm2m/pom.xml index bdbb0ac1b8..22ef3ce5cc 100644 --- a/msa/transport/lwm2m/pom.xml +++ b/msa/transport/lwm2m/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.msa - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT transport org.thingsboard.msa.transport diff --git a/msa/transport/mqtt/pom.xml b/msa/transport/mqtt/pom.xml index 59b0159c53..f03239819c 100644 --- a/msa/transport/mqtt/pom.xml +++ b/msa/transport/mqtt/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.msa - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT transport org.thingsboard.msa.transport diff --git a/msa/transport/pom.xml b/msa/transport/pom.xml index 4d329580c5..4294338095 100644 --- a/msa/transport/pom.xml +++ b/msa/transport/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/transport/snmp/pom.xml b/msa/transport/snmp/pom.xml index dad9811938..7393134afd 100644 --- a/msa/transport/snmp/pom.xml +++ b/msa/transport/snmp/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa transport - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT org.thingsboard.msa.transport diff --git a/msa/vc-executor-docker/pom.xml b/msa/vc-executor-docker/pom.xml index 7c83bd32c3..716e3251e2 100644 --- a/msa/vc-executor-docker/pom.xml +++ b/msa/vc-executor-docker/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/vc-executor/pom.xml b/msa/vc-executor/pom.xml index fdb077ec4b..4cfa159be1 100644 --- a/msa/vc-executor/pom.xml +++ b/msa/vc-executor/pom.xml @@ -10,7 +10,7 @@ org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/web-ui/package.json b/msa/web-ui/package.json index 0f707a216a..b59b2b267f 100644 --- a/msa/web-ui/package.json +++ b/msa/web-ui/package.json @@ -1,7 +1,7 @@ { "name": "thingsboard-web-ui", "private": true, - "version": "4.3.1.8", + "version": "4.3.1.9", "description": "ThingsBoard Web UI Microservice", "main": "server.ts", "bin": "server.js", diff --git a/msa/web-ui/pom.xml b/msa/web-ui/pom.xml index 3b402e2081..22dc5e3d2d 100644 --- a/msa/web-ui/pom.xml +++ b/msa/web-ui/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT msa org.thingsboard.msa diff --git a/netty-mqtt/pom.xml b/netty-mqtt/pom.xml index 535098bd40..0683709785 100644 --- a/netty-mqtt/pom.xml +++ b/netty-mqtt/pom.xml @@ -8,11 +8,11 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT thingsboard netty-mqtt - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT jar Netty MQTT Client diff --git a/pom.xml b/pom.xml index 5a24a8bffd..71b139b25e 100755 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT pom Thingsboard diff --git a/rest-client/pom.xml b/rest-client/pom.xml index e76b66f399..2f46c7df1f 100644 --- a/rest-client/pom.xml +++ b/rest-client/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT thingsboard rest-client diff --git a/rule-engine/pom.xml b/rule-engine/pom.xml index da03f67a7b..5321e515d8 100644 --- a/rule-engine/pom.xml +++ b/rule-engine/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT thingsboard rule-engine diff --git a/rule-engine/rule-engine-api/pom.xml b/rule-engine/rule-engine-api/pom.xml index 9499a72abf..ef94a32017 100644 --- a/rule-engine/rule-engine-api/pom.xml +++ b/rule-engine/rule-engine-api/pom.xml @@ -11,7 +11,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT rule-engine org.thingsboard.rule-engine diff --git a/rule-engine/rule-engine-components/pom.xml b/rule-engine/rule-engine-components/pom.xml index 7aad9bedc4..28c1b03ad2 100644 --- a/rule-engine/rule-engine-components/pom.xml +++ b/rule-engine/rule-engine-components/pom.xml @@ -11,7 +11,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT rule-engine org.thingsboard.rule-engine diff --git a/tools/pom.xml b/tools/pom.xml index 2259506fe0..9426d51039 100644 --- a/tools/pom.xml +++ b/tools/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT thingsboard tools diff --git a/transport/coap/pom.xml b/transport/coap/pom.xml index e94ebe5f20..dd6f48adfe 100644 --- a/transport/coap/pom.xml +++ b/transport/coap/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT transport org.thingsboard.transport diff --git a/transport/http/pom.xml b/transport/http/pom.xml index e92c9f7ee3..62ed3e5be5 100644 --- a/transport/http/pom.xml +++ b/transport/http/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT transport org.thingsboard.transport diff --git a/transport/lwm2m/pom.xml b/transport/lwm2m/pom.xml index e7529c74ed..b20cf6a91c 100644 --- a/transport/lwm2m/pom.xml +++ b/transport/lwm2m/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT transport org.thingsboard.transport diff --git a/transport/mqtt/pom.xml b/transport/mqtt/pom.xml index 00805a92af..af89ac68b0 100644 --- a/transport/mqtt/pom.xml +++ b/transport/mqtt/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT transport org.thingsboard.transport diff --git a/transport/pom.xml b/transport/pom.xml index 50a2003b1c..734636b5f3 100644 --- a/transport/pom.xml +++ b/transport/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT thingsboard transport diff --git a/transport/snmp/pom.xml b/transport/snmp/pom.xml index 0ebbcc412e..35812d7d07 100644 --- a/transport/snmp/pom.xml +++ b/transport/snmp/pom.xml @@ -10,7 +10,7 @@ org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT transport diff --git a/ui-ngx/package.json b/ui-ngx/package.json index ad67831865..0281499027 100644 --- a/ui-ngx/package.json +++ b/ui-ngx/package.json @@ -1,6 +1,6 @@ { "name": "thingsboard", - "version": "4.3.1.8", + "version": "4.3.1.9", "scripts": { "ng": "ng", "start": "node --max_old_space_size=8048 ./node_modules/@angular/cli/bin/ng serve --configuration development --host 0.0.0.0 --open", diff --git a/ui-ngx/pom.xml b/ui-ngx/pom.xml index f1f5004c90..e1bae5c390 100644 --- a/ui-ngx/pom.xml +++ b/ui-ngx/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.3.1.8-SNAPSHOT + 4.3.1.9-SNAPSHOT thingsboard org.thingsboard From 42d720cef5e1f736f76fe8ea9a39a463273d109f Mon Sep 17 00:00:00 2001 From: dshvaika Date: Fri, 13 Nov 2026 11:11:46 +0200 Subject: [PATCH 19/21] IoT Hub: the device package removal lists the kept entities in a hint that says why they stay --- .../iot-hub/iot-hub-delete-dialog.component.html | 9 ++++++++- .../iot-hub/iot-hub-delete-dialog.component.ts | 12 +++++++----- ui-ngx/src/assets/locale/locale.constant-en_US.json | 9 +++++---- 3 files changed, 20 insertions(+), 10 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html index 3de67878aa..f7bcce1201 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html @@ -9,7 +9,14 @@

{{ 'iot-hub.remove-confirm-title' | translate:{ name: data.itemName } }}

{{ description }}

@if (keptReferences) { - +
+ info_outline +
+
{{ keptTitle }}
+
{{ keptReason }}
+ +
+
}
diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts index 08ae924eb6..88bdf96fff 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts @@ -32,6 +32,8 @@ export class TbIotHubDeleteDialogComponent extends DialogComponent, @@ -42,15 +44,15 @@ export class TbIotHubDeleteDialogComponent extends DialogComponent ({ id: entity.entityId as EntityId, name: entity.name })); // Kept because other packages use them, because the user had them before the package, or both - const key = !kept.usedExistingCount ? 'iot-hub.remove-desc-kept' : - !kept.usedByItemsCount ? 'iot-hub.remove-desc-kept-own' : 'iot-hub.remove-desc-kept-own-or-used'; - this.description = this.translate.instant(key, { count: kept.usedByItemsCount, kept: kept.entities.length }); - } else { - this.description = this.translate.instant(data.itemType === 'SOLUTION_TEMPLATE' ? 'iot-hub.remove-desc-solution-template' : 'iot-hub.remove-desc'); + const reasonKey = !kept.usedExistingCount ? 'iot-hub.remove-kept-used' : + !kept.usedByItemsCount ? 'iot-hub.remove-kept-own' : 'iot-hub.remove-kept-own-or-used'; + this.keptTitle = this.translate.instant('iot-hub.remove-kept-title', { kept: kept.entities.length }); + this.keptReason = this.translate.instant(reasonKey, { kept: kept.entities.length }); } } diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index fe7490032a..88b545b9d2 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -6445,10 +6445,11 @@ "install-success-desc": "'{{name}}' has been installed successfully", "remove": "Remove", "remove-confirm-title": "Remove '{{name}}'?", - "remove-desc": "Removing this will also remove the installed entity and its associated resources within your tenant", - "remove-desc-kept-own": "Removing this will also remove the installed entity and its associated resources within your tenant. The following { kept, plural, =1 {entity will not be removed, because you had it} other {entities will not be removed, because you had them} } before the package was installed:", - "remove-desc-kept-own-or-used": "Removing this will also remove the installed entity and its associated resources within your tenant. The following { kept, plural, =1 {entity will not be removed, because you had it before the package was installed or it is used by} other {entities will not be removed, because you had them before the package was installed or they are used by} } { count, plural, =1 {1 other installed package} other {# other installed packages} }:", - "remove-desc-kept": "Removing this will also remove the installed entity and its associated resources within your tenant. The following { kept, plural, =1 {entity will not be removed, because it is} other {entities will not be removed, because they are} } used by { count, plural, =1 {1 other installed package} other {# other installed packages} }:", + "remove-desc": "Removing this will also remove the installed entity and its associated resources within your tenant.", + "remove-kept-title": "{ kept, plural, =1 {This entity will not be removed} other {These entities will not be removed} }", + "remove-kept-used": "Other installed packages use { kept, plural, =1 {it} other {them} }.", + "remove-kept-own": "You had { kept, plural, =1 {it} other {them} } before the package was installed.", + "remove-kept-own-or-used": "You had { kept, plural, =1 {it} other {them} } before the package was installed, or other installed packages use { kept, plural, =1 {it} other {them} }.", "remove-desc-solution-template": "Removing this solution template will also remove all created entities including dashboards, rule chains, devices, and other associated resources within your tenant", "remove-anyway": "Remove anyway", "select-entity-for-cf": "Select entity for calculated field '{{name}}'", From 5b487284f0d0e38232227f39ca14fb28bb4f65a8 Mon Sep 17 00:00:00 2001 From: Sergey Matvienko Date: Fri, 13 Nov 2026 10:37:52 +0100 Subject: [PATCH 20/21] Fix license header in TbAbstractSubCtxTest --- .../server/service/subscription/TbAbstractSubCtxTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/application/src/test/java/org/thingsboard/server/service/subscription/TbAbstractSubCtxTest.java b/application/src/test/java/org/thingsboard/server/service/subscription/TbAbstractSubCtxTest.java index 01ffe38317..588f1749ff 100644 --- a/application/src/test/java/org/thingsboard/server/service/subscription/TbAbstractSubCtxTest.java +++ b/application/src/test/java/org/thingsboard/server/service/subscription/TbAbstractSubCtxTest.java @@ -1,4 +1,4 @@ -// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors // SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.service.subscription; From 9076bd75fc054cbf53e9d4b5a74c30e19a110a79 Mon Sep 17 00:00:00 2001 From: Vladyslav_Prykhodko Date: Fri, 13 Nov 2026 12:37:45 +0200 Subject: [PATCH 21/21] Fix license headers in TbAbstractSubCtxTest and AfterStartUp --- .../server/service/subscription/TbAbstractSubCtxTest.java | 2 +- .../java/org/thingsboard/server/queue/util/AfterStartUp.java | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/application/src/test/java/org/thingsboard/server/service/subscription/TbAbstractSubCtxTest.java b/application/src/test/java/org/thingsboard/server/service/subscription/TbAbstractSubCtxTest.java index 588f1749ff..01ffe38317 100644 --- a/application/src/test/java/org/thingsboard/server/service/subscription/TbAbstractSubCtxTest.java +++ b/application/src/test/java/org/thingsboard/server/service/subscription/TbAbstractSubCtxTest.java @@ -1,4 +1,4 @@ -// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.service.subscription; diff --git a/common/queue/src/main/java/org/thingsboard/server/queue/util/AfterStartUp.java b/common/queue/src/main/java/org/thingsboard/server/queue/util/AfterStartUp.java index 28b5e180d4..097f760d88 100644 --- a/common/queue/src/main/java/org/thingsboard/server/queue/util/AfterStartUp.java +++ b/common/queue/src/main/java/org/thingsboard/server/queue/util/AfterStartUp.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.queue.util; import org.springframework.boot.context.event.ApplicationReadyEvent;