You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ambari.apache.org by ji...@apache.org on 2026/08/17 03:31:18 UTC
(ambari) branch frontend-refactor updated: AMBARI-26627: Align React Services and Configs workflows with Classic Ambari (#4170)
This is an automated email from the ASF dual-hosted git repository.
JiaLiangC pushed a commit to branch frontend-refactor
in repository https://gitbox.apache.org/repos/asf/ambari.git
The following commit(s) were added to refs/heads/frontend-refactor by this push:
new 0fd3e1530b AMBARI-26627: Align React Services and Configs workflows with Classic Ambari (#4170)
0fd3e1530b is described below
commit 0fd3e1530b30a24c2e0181ea66e8e09a58f6262b
Author: jialiang <ji...@gmail.com>
AuthorDate: Mon Aug 17 11:31:12 2026 +0800
AMBARI-26627: Align React Services and Configs workflows with Classic Ambari (#4170)
* AMBARI-26627: Align React Services and Configs workflows with Classic Ambari
* AMBARI-26627: Add JIRA link to generated pull requests
---
.../addServicePersistence.ts} | 34 +-
.../latest/src/Utils/configGroupSavePlan.test.ts | 124 ++++++
ambari-web/latest/src/Utils/configGroupSavePlan.ts | 97 +++++
.../src/Utils/customConfigProperties.test.ts | 62 +++
.../latest/src/Utils/customConfigProperties.ts | 107 ++++++
ambari-web/latest/src/Utils/flumeAgents.test.ts | 86 +++++
ambari-web/latest/src/Utils/flumeAgents.ts | 97 +++++
ambari-web/latest/src/Utils/quicklinks.test.ts | 62 +++
ambari-web/latest/src/Utils/quicklinks.ts | 67 ++++
.../src/Utils/reassignManualCommands.test.ts | 100 +++++
.../latest/src/Utils/reassignManualCommands.ts | 140 +++++++
.../latest/src/Utils/reassignValidation.test.ts | 110 ++++++
ambari-web/latest/src/Utils/reassignValidation.ts | 120 ++++++
.../latest/src/Utils/serviceGlobalActions.test.ts | 51 +++
.../latest/src/Utils/serviceNavigation.test.ts | 73 ++++
ambari-web/latest/src/Utils/serviceNavigation.ts | 69 ++++
.../servicePermissions.ts} | 21 +-
.../latest/src/Utils/servicesConfigsPolicy.test.ts | 79 ++++
.../latest/src/Utils/sslProtocolUtils.test.ts | 76 ++++
ambari-web/latest/src/Utils/sslProtocolUtils.ts | 15 +-
ambari-web/latest/src/api/configsApi.ts | 4 +-
ambari-web/latest/src/api/quicklinksApi.ts | 15 +-
ambari-web/latest/src/api/serviceApi.ts | 63 ++-
ambari-web/latest/src/api/serviceConfigApi.ts | 6 +-
.../latest/src/api/servicesConfigsApi.test.ts | 136 +++++++
.../components/ServiceOperationRouteGuard.test.tsx | 64 +++
.../ServiceOperationRouteGuard.tsx} | 27 +-
.../src/components/Sidebar/RunAllServiceCheck.tsx | 9 +-
.../latest/src/components/Sidebar/SidebarItem.tsx | 188 ++++++---
.../latest/src/hooks/useConfigSaver.test.tsx | 170 ++++++++
ambari-web/latest/src/hooks/useConfigSaver.tsx | 59 +--
ambari-web/latest/src/hooks/useLazyQuicklinks.ts | 168 +++++---
ambari-web/latest/src/router/RoutesList.tsx | 61 ++-
.../latest/src/screens/ClusterWizard/Step10.tsx | 22 +-
.../src/screens/CommonConfigs/AdvancedConfigs.tsx | 108 ++----
.../screens/CommonConfigs/ChooseConfigGroup.tsx | 7 +-
.../screens/CommonConfigs/TestConnection.test.tsx | 235 ++++++++++++
.../src/screens/CommonConfigs/TestConnection.tsx | 84 +++-
.../screens/ConfigGroups/ManageConfigGroups.tsx | 287 +++++++-------
.../ConfigGroups/SelectConfigGroupHosts.tsx | 9 +-
.../src/screens/ConfigVersions/VersionsList.tsx | 28 +-
.../latest/src/screens/ServiceConfigs/index.tsx | 20 +-
ambari-web/latest/src/screens/Services/Actions.tsx | 104 ++---
.../AddServiceWizard/wizardDataStore/context.tsx | 46 ++-
.../src/screens/Services/AddWizardUrlMapping.tsx | 104 ++---
.../src/screens/Services/FlumeSummary.test.tsx | 194 ++++++++++
.../latest/src/screens/Services/FlumeSummary.tsx | 262 +++++++++++++
.../src/screens/Services/ServiceComponents.tsx | 3 +
.../src/screens/Services/ServiceDashboard.tsx | 126 +++---
.../latest/src/screens/Services/reassign/Step4.tsx | 126 +++++-
.../latest/src/screens/Services/reassign/Step5.tsx | 13 +
.../src/screens/Services/reassign/ValidateMove.tsx | 295 +++++++++-----
.../latest/src/screens/Services/reassign/index.tsx | 14 +
.../screens/Services/reassign/store/context.tsx | 13 +-
ambari-web/latest/src/store/ServiceContext.tsx | 3 +
dev-support/ambari-ai/README.md | 3 +-
dev-support/ambari-ai/ambari_ai.py | 6 +-
dev-support/ambari-ai/test_ambari_ai.py | 7 +
.../react-current/04-services-configs-gap.md | 427 +++++++++++++++++++++
59 files changed, 4300 insertions(+), 806 deletions(-)
diff --git a/ambari-web/latest/src/api/quicklinksApi.ts b/ambari-web/latest/src/Utils/addServicePersistence.ts
similarity index 58%
copy from ambari-web/latest/src/api/quicklinksApi.ts
copy to ambari-web/latest/src/Utils/addServicePersistence.ts
index c97d482776..41772b5178 100644
--- a/ambari-web/latest/src/api/quicklinksApi.ts
+++ b/ambari-web/latest/src/Utils/addServicePersistence.ts
@@ -16,15 +16,27 @@
* limitations under the License.
*/
-import { ambariApi } from "./config/axiosConfig";
+import ClusterApi from "../api/clusterApi";
-export const QuicklinksApi = {
- getQuicklinks: async (stackVersion: string,stackName:string, serviceName: string) => {
- const url = `/stacks/${stackName}/versions/${stackVersion}/services/${serviceName}/quicklinks?QuickLinkInfo/default=true&fields=*&_=${Date.now()}'`;
- const response = await ambariApi.request({
- url: url,
- method: "GET",
- });
- return response;
- }
-}
\ No newline at end of file
+export const CANCEL_ADD_SERVICE_WIZARD_EVENT =
+ "ambari:cancel-add-service-wizard";
+
+export const buildClearedAddServiceState = (
+ initialState: object,
+ requestSequence = 0
+) =>
+ JSON.stringify({
+ ADD_SERVICE: JSON.stringify({
+ ...initialState,
+ requestSequence,
+ }),
+ CLUSTER_STATE: JSON.stringify({}),
+ });
+
+export const clearAddServiceWizardState = (
+ initialState: object,
+ requestSequence = 0
+) =>
+ ClusterApi.postPersistData(
+ buildClearedAddServiceState(initialState, requestSequence)
+ );
diff --git a/ambari-web/latest/src/Utils/configGroupSavePlan.test.ts b/ambari-web/latest/src/Utils/configGroupSavePlan.test.ts
new file mode 100644
index 0000000000..468ce25d74
--- /dev/null
+++ b/ambari-web/latest/src/Utils/configGroupSavePlan.test.ts
@@ -0,0 +1,124 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import { describe, expect, it } from "vitest";
+import {
+ buildConfigGroupUpdatePlan,
+ moveHostsToConfigGroup,
+ removeConfigGroupAndReturnHosts,
+} from "./configGroupSavePlan";
+
+const group = (id: number, hosts: string[]) => ({
+ ConfigGroup: {
+ id,
+ hosts: hosts.map((host_name) => ({ host_name })),
+ },
+});
+
+describe("config group save planning", () => {
+ it("clears every changed group before writing swapped memberships", () => {
+ const previous = [group(1, ["host1"]), group(2, ["host2"])];
+ const updated = [group(1, ["host2"]), group(2, ["host1"])];
+
+ const plan = buildConfigGroupUpdatePlan(previous, updated);
+
+ expect(plan.toClear).toEqual(updated);
+ expect(plan.toSet).toEqual(updated);
+ });
+
+ it("does not rewrite a group whose final membership is empty", () => {
+ const previous = [group(1, ["host1"])];
+ const updated = [group(1, [])];
+
+ const plan = buildConfigGroupUpdatePlan(previous, updated);
+
+ expect(plan.toClear).toEqual(updated);
+ expect(plan.toSet).toEqual([]);
+ });
+
+ it("writes metadata-only updates without a membership clear", () => {
+ const previous = [group(1, ["host1"])];
+ const updated = [group(1, ["host1"])];
+
+ const plan = buildConfigGroupUpdatePlan(previous, updated);
+
+ expect(plan.toClear).toEqual([]);
+ expect(plan.toSet).toEqual(updated);
+ });
+});
+
+describe("config group membership editing", () => {
+ it("moves hosts between non-default groups in one state transition", () => {
+ const groups = [
+ {
+ ...group(1, ["host1"]),
+ ConfigGroup: {
+ ...group(1, ["host1"]).ConfigGroup,
+ group_name: "A",
+ },
+ },
+ {
+ ...group(2, ["host2"]),
+ ConfigGroup: {
+ ...group(2, ["host2"]).ConfigGroup,
+ group_name: "B",
+ },
+ },
+ ];
+
+ expect(moveHostsToConfigGroup(groups, "B", ["host1"])).toEqual([
+ { ConfigGroup: { id: 1, group_name: "A", hosts: [] } },
+ {
+ ConfigGroup: {
+ id: 2,
+ group_name: "B",
+ hosts: [{ host_name: "host2" }, { host_name: "host1" }],
+ },
+ },
+ ]);
+ });
+
+ it("returns deleted group hosts to Default", () => {
+ const groups = [
+ {
+ ...group(0, ["host2"]),
+ ConfigGroup: {
+ ...group(0, ["host2"]).ConfigGroup,
+ group_name: "Default",
+ },
+ },
+ {
+ ...group(1, ["host1"]),
+ ConfigGroup: {
+ ...group(1, ["host1"]).ConfigGroup,
+ group_name: "A",
+ },
+ },
+ ];
+
+ expect(removeConfigGroupAndReturnHosts(groups, "A")).toEqual([
+ {
+ ConfigGroup: {
+ id: 0,
+ group_name: "Default",
+ hosts: [{ host_name: "host2" }, { host_name: "host1" }],
+ },
+ },
+ ]);
+ });
+});
diff --git a/ambari-web/latest/src/Utils/configGroupSavePlan.ts b/ambari-web/latest/src/Utils/configGroupSavePlan.ts
new file mode 100644
index 0000000000..d60b268652
--- /dev/null
+++ b/ambari-web/latest/src/Utils/configGroupSavePlan.ts
@@ -0,0 +1,97 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+export type ConfigGroupLike = {
+ ConfigGroup: {
+ id?: string | number;
+ group_name?: string;
+ hosts?: Array<{ host_name?: string }>;
+ };
+};
+
+const getHostNames = (configGroup: ConfigGroupLike) =>
+ new Set(
+ (configGroup.ConfigGroup.hosts || [])
+ .map((host) => host.host_name)
+ .filter((hostName): hostName is string => Boolean(hostName))
+ );
+
+const hasSameHosts = (first: Set<string>, second: Set<string>) =>
+ first.size === second.size && [...first].every((host) => second.has(host));
+
+export const buildConfigGroupUpdatePlan = <T extends ConfigGroupLike>(
+ previousGroups: T[],
+ updatedGroups: T[]
+) => {
+ const previousById = new Map(
+ previousGroups.map((group) => [group.ConfigGroup.id, group])
+ );
+ const toClear = updatedGroups.filter((group) => {
+ const previous = previousById.get(group.ConfigGroup.id);
+ return (
+ previous && !hasSameHosts(getHostNames(previous), getHostNames(group))
+ );
+ });
+ const clearSet = new Set(toClear);
+ const toSet = updatedGroups.filter(
+ (group) => !clearSet.has(group) || getHostNames(group).size > 0
+ );
+
+ return { toClear, toSet };
+};
+
+export const moveHostsToConfigGroup = <T extends ConfigGroupLike>(
+ groups: T[],
+ targetGroupName: string,
+ hostsToMove: string[]
+): T[] => {
+ const movedHosts = new Set(hostsToMove);
+ return groups.map((group) => {
+ const remainingHosts = (group.ConfigGroup.hosts || []).filter(
+ (host) => !host.host_name || !movedHosts.has(host.host_name)
+ );
+ const targetHosts =
+ group.ConfigGroup.group_name === targetGroupName
+ ? [
+ ...remainingHosts,
+ ...hostsToMove.map((host_name) => ({ host_name })),
+ ]
+ : remainingHosts;
+ return {
+ ...group,
+ ConfigGroup: {
+ ...group.ConfigGroup,
+ hosts: targetHosts,
+ },
+ };
+ });
+};
+
+export const removeConfigGroupAndReturnHosts = <T extends ConfigGroupLike>(
+ groups: T[],
+ groupName: string,
+ defaultGroupName = "Default"
+): T[] => {
+ const removedGroup = groups.find(
+ (group) => group.ConfigGroup.group_name === groupName
+ );
+ const hostNames = [...getHostNames(removedGroup || { ConfigGroup: {} })];
+ return moveHostsToConfigGroup(groups, defaultGroupName, hostNames).filter(
+ (group) => group.ConfigGroup.group_name !== groupName
+ );
+};
diff --git a/ambari-web/latest/src/Utils/customConfigProperties.test.ts b/ambari-web/latest/src/Utils/customConfigProperties.test.ts
new file mode 100644
index 0000000000..8c2661af2d
--- /dev/null
+++ b/ambari-web/latest/src/Utils/customConfigProperties.test.ts
@@ -0,0 +1,62 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import { describe, expect, it } from "vitest";
+import {
+ parseCustomPropertyInput,
+ validateCustomPropertyKey,
+} from "./customConfigProperties";
+
+describe("custom config properties", () => {
+ it("parses multiple properties and preserves equals signs in values", () => {
+ expect(
+ parseCustomPropertyInput("first=value\nsecond=a=b=c")
+ ).toEqual({
+ properties: [
+ { key: "first", value: "value" },
+ { key: "second", value: "a=b=c" },
+ ],
+ errors: [],
+ });
+ });
+
+ it("reports format, key, duplicate, and existing-property errors", () => {
+ const result = parseCustomPropertyInput(
+ "missing separator\n\n=empty\nbad key=value\nduplicate=1\nduplicate=2\nsaved=3",
+ { saved: { value: "current", isVisible: true } }
+ );
+
+ expect(result.errors).toEqual([
+ "Line 1: Invalid format. Expected key=value",
+ "Line 3: Key cannot be empty",
+ 'Line 4: Invalid key "bad key". Only alphanumerics, hyphens, underscores, asterisks and periods are allowed.',
+ 'Line 6: Duplicate key "duplicate"',
+ 'Line 7: Property "saved" already exists',
+ ]);
+ expect(result.properties).toEqual([{ key: "duplicate", value: "1" }]);
+ });
+
+ it("allows a removed property to be added again", () => {
+ const removed = { saved: { value: null, isVisible: false } };
+
+ expect(validateCustomPropertyKey(" saved ", removed)).toBe("");
+ expect(parseCustomPropertyInput("saved=new", removed).errors).toEqual([]);
+ expect(validateCustomPropertyKey("saved", { saved: { value: "old" } }))
+ .toBe('Property "saved" already exists');
+ });
+});
diff --git a/ambari-web/latest/src/Utils/customConfigProperties.ts b/ambari-web/latest/src/Utils/customConfigProperties.ts
new file mode 100644
index 0000000000..4b55816057
--- /dev/null
+++ b/ambari-web/latest/src/Utils/customConfigProperties.ts
@@ -0,0 +1,107 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import { configValidator } from "./validators";
+
+export type ExistingCustomProperty = {
+ isVisible?: boolean;
+ value?: unknown;
+};
+
+export type ParsedCustomProperty = {
+ key: string;
+ value: string;
+};
+
+export function validateCustomPropertyKey(
+ key: string,
+ existingProperties: Record<string, ExistingCustomProperty> = {}
+): string {
+ const normalizedKey = key.trim();
+ if (!normalizedKey) {
+ return "Property key is required";
+ }
+ if (!configValidator.isValidConfigKey(normalizedKey)) {
+ return "Invalid key. Only alphanumerics, hyphens, underscores, asterisks and periods are allowed.";
+ }
+
+ const existingProperty = existingProperties[normalizedKey];
+ if (
+ existingProperty &&
+ existingProperty.isVisible !== false &&
+ existingProperty.value !== null
+ ) {
+ return `Property "${normalizedKey}" already exists`;
+ }
+ return "";
+}
+
+export function parseCustomPropertyInput(
+ input: string,
+ existingProperties: Record<string, ExistingCustomProperty> = {}
+): { properties: ParsedCustomProperty[]; errors: string[] } {
+ const properties: ParsedCustomProperty[] = [];
+ const errors: string[] = [];
+ const seenKeys = new Set<string>();
+
+ input.split(/\r?\n/).forEach((rawLine, index) => {
+ const line = rawLine.trim();
+ if (!line) {
+ return;
+ }
+
+ const lineNumber = index + 1;
+ const equalIndex = line.indexOf("=");
+ if (equalIndex < 0) {
+ errors.push(`Line ${lineNumber}: Invalid format. Expected key=value`);
+ return;
+ }
+
+ const key = line.substring(0, equalIndex).trim();
+ const value = line.substring(equalIndex + 1).trim();
+ if (!key) {
+ errors.push(`Line ${lineNumber}: Key cannot be empty`);
+ return;
+ }
+ if (!configValidator.isValidConfigKey(key)) {
+ errors.push(
+ `Line ${lineNumber}: Invalid key "${key}". Only alphanumerics, hyphens, underscores, asterisks and periods are allowed.`
+ );
+ return;
+ }
+ if (seenKeys.has(key)) {
+ errors.push(`Line ${lineNumber}: Duplicate key "${key}"`);
+ return;
+ }
+
+ const existingProperty = existingProperties[key];
+ if (
+ existingProperty &&
+ existingProperty.isVisible !== false &&
+ existingProperty.value !== null
+ ) {
+ errors.push(`Line ${lineNumber}: Property "${key}" already exists`);
+ return;
+ }
+
+ seenKeys.add(key);
+ properties.push({ key, value });
+ });
+
+ return { properties, errors };
+}
diff --git a/ambari-web/latest/src/Utils/flumeAgents.test.ts b/ambari-web/latest/src/Utils/flumeAgents.test.ts
new file mode 100644
index 0000000000..f881e790b2
--- /dev/null
+++ b/ambari-web/latest/src/Utils/flumeAgents.test.ts
@@ -0,0 +1,86 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import { describe, expect, it } from "vitest";
+import {
+ canStartFlumeAgent,
+ canStopFlumeAgent,
+ extractFlumeAgents,
+} from "./flumeAgents";
+
+describe("Flume agents", () => {
+ it("extracts and sorts handlers by host and name", () => {
+ expect(
+ extractFlumeAgents([
+ {
+ ServiceComponentInfo: {
+ service_name: "FLUME",
+ component_name: "FLUME_HANDLER",
+ },
+ host_components: [
+ {
+ HostRoles: { host_name: "host-b" },
+ processes: [
+ { HostComponentProcess: { name: "agent-2", status: "RUNNING" } },
+ ],
+ },
+ {
+ HostRoles: { host_name: "host-a" },
+ processes: [
+ {
+ HostComponentProcess: {
+ host_name: "public-agent-host",
+ name: "agent-1",
+ status: "NOT_RUNNING",
+ },
+ },
+ { HostComponentProcess: { name: "agent-unknown", status: "BROKEN" } },
+ ],
+ },
+ ],
+ },
+ ])
+ ).toEqual([
+ {
+ id: "agent-unknown-host-a",
+ hostName: "host-a",
+ name: "agent-unknown",
+ status: "UNKNOWN",
+ },
+ {
+ id: "agent-2-host-b",
+ hostName: "host-b",
+ name: "agent-2",
+ status: "RUNNING",
+ },
+ {
+ id: "agent-1-public-agent-host",
+ hostName: "public-agent-host",
+ name: "agent-1",
+ status: "NOT_RUNNING",
+ },
+ ]);
+ });
+
+ it("allows only classic state-valid actions", () => {
+ expect(canStartFlumeAgent("NOT_RUNNING")).toBe(true);
+ expect(canStartFlumeAgent("RUNNING")).toBe(false);
+ expect(canStopFlumeAgent("RUNNING")).toBe(true);
+ expect(canStopFlumeAgent("UNKNOWN")).toBe(false);
+ });
+});
diff --git a/ambari-web/latest/src/Utils/flumeAgents.ts b/ambari-web/latest/src/Utils/flumeAgents.ts
new file mode 100644
index 0000000000..d967af7104
--- /dev/null
+++ b/ambari-web/latest/src/Utils/flumeAgents.ts
@@ -0,0 +1,97 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+export type FlumeAgentStatus = "RUNNING" | "NOT_RUNNING" | "UNKNOWN";
+
+export type FlumeAgent = {
+ id: string;
+ hostName: string;
+ name: string;
+ status: FlumeAgentStatus;
+};
+
+type FlumeProcess = {
+ HostComponentProcess?: {
+ host_name?: string;
+ name?: string;
+ status?: unknown;
+ };
+};
+
+type FlumeHostComponent = {
+ HostRoles?: { host_name?: string };
+ processes?: FlumeProcess[];
+};
+
+type ServiceComponent = {
+ ServiceComponentInfo?: {
+ component_name?: string;
+ service_name?: string;
+ };
+ host_components?: FlumeHostComponent[];
+};
+
+const normalizeStatus = (status: unknown): FlumeAgentStatus => {
+ if (status === "RUNNING" || status === "NOT_RUNNING") {
+ return status;
+ }
+ return "UNKNOWN";
+};
+
+export function extractFlumeAgents(componentData: unknown): FlumeAgent[] {
+ const items = Array.isArray(componentData)
+ ? componentData as ServiceComponent[]
+ : Array.isArray((componentData as { items?: unknown[] })?.items)
+ ? (componentData as { items: ServiceComponent[] }).items
+ : [];
+
+ const flumeComponent = items.find(
+ (item) =>
+ item?.ServiceComponentInfo?.service_name === "FLUME" &&
+ item?.ServiceComponentInfo?.component_name === "FLUME_HANDLER"
+ );
+
+ return (flumeComponent?.host_components || [])
+ .flatMap((hostComponent) => {
+ const componentHostName = hostComponent?.HostRoles?.host_name;
+ return (hostComponent?.processes || []).map((process) => {
+ const processInfo = process?.HostComponentProcess || {};
+ const hostName = processInfo.host_name || componentHostName || "";
+ const name = processInfo.name || "";
+ return {
+ id: `${name}-${hostName}`,
+ hostName,
+ name,
+ status: normalizeStatus(processInfo.status),
+ };
+ });
+ })
+ .filter((agent: FlumeAgent) => agent.hostName && agent.name)
+ .sort((left: FlumeAgent, right: FlumeAgent) =>
+ left.hostName.localeCompare(right.hostName) ||
+ left.name.localeCompare(right.name)
+ );
+}
+
+export function canStartFlumeAgent(status: FlumeAgentStatus): boolean {
+ return status === "NOT_RUNNING";
+}
+
+export function canStopFlumeAgent(status: FlumeAgentStatus): boolean {
+ return status === "RUNNING";
+}
diff --git a/ambari-web/latest/src/Utils/quicklinks.test.ts b/ambari-web/latest/src/Utils/quicklinks.test.ts
new file mode 100644
index 0000000000..e88067b091
--- /dev/null
+++ b/ambari-web/latest/src/Utils/quicklinks.test.ts
@@ -0,0 +1,62 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import { describe, expect, it } from "vitest";
+import {
+ createPublicHostNameMap,
+ resolveQuicklinkConfigPlaceholders,
+ substituteQuicklinkTemplate,
+} from "./quicklinks";
+
+describe("quick link resolution", () => {
+ it("substitutes protocol, public host, port, and the logged-in user", () => {
+ expect(
+ substituteQuicklinkTemplate(
+ "%@://%@:%@/login?user=%@",
+ "https",
+ "public.example",
+ "8443",
+ "operator",
+ true
+ )
+ ).toBe("https://public.example:8443/login?user=operator");
+ });
+
+ it("resolves config references and preserves unknown references", () => {
+ expect(
+ resolveQuicklinkConfigPlaceholders(
+ "https://host:${core-site/http.port}/${missing/value}",
+ [{ type: "core-site", properties: { "http.port": 9870 } }]
+ )
+ ).toBe("https://host:9870/${missing/value}");
+ });
+
+ it("maps internal hosts to public hosts without inventing missing values", () => {
+ expect(
+ createPublicHostNameMap([
+ {
+ Hosts: {
+ host_name: "internal-1",
+ public_host_name: "public-1",
+ },
+ },
+ { Hosts: { host_name: "internal-2" } },
+ ])
+ ).toEqual(new Map([["internal-1", "public-1"]]));
+ });
+});
diff --git a/ambari-web/latest/src/Utils/quicklinks.ts b/ambari-web/latest/src/Utils/quicklinks.ts
new file mode 100644
index 0000000000..28c606235a
--- /dev/null
+++ b/ambari-web/latest/src/Utils/quicklinks.ts
@@ -0,0 +1,67 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+export type QuicklinkConfiguration = {
+ type: string;
+ properties?: Record<string, unknown>;
+};
+
+export function substituteQuicklinkTemplate(
+ template: string,
+ protocol: string,
+ host: string,
+ port: string,
+ username: string,
+ requiresUsername: boolean
+): string {
+ const replacements = requiresUsername
+ ? [protocol, host, port, username]
+ : [protocol, host, port];
+ let index = 0;
+ return template.replace(/%@/g, () => replacements[index++] ?? "");
+}
+
+export function resolveQuicklinkConfigPlaceholders(
+ url: string,
+ configurations: QuicklinkConfiguration[]
+): string {
+ return url.replace(
+ /\$\{([^/{}\s]+)\/([^{}\s]+)\}/g,
+ (placeholder, configType: string, propertyName: string) => {
+ const configuration = configurations.find(
+ (candidate) => candidate.type === configType
+ );
+ const value = configuration?.properties?.[propertyName];
+ return value === undefined || value === null ? placeholder : String(value);
+ }
+ );
+}
+
+export function createPublicHostNameMap(
+ items: Array<{ Hosts?: { host_name?: string; public_host_name?: string } }>
+): Map<string, string> {
+ const result = new Map<string, string>();
+ items.forEach((item) => {
+ const hostName = item.Hosts?.host_name;
+ const publicHostName = item.Hosts?.public_host_name;
+ if (hostName && publicHostName) {
+ result.set(hostName, publicHostName);
+ }
+ });
+ return result;
+}
diff --git a/ambari-web/latest/src/Utils/reassignManualCommands.test.ts b/ambari-web/latest/src/Utils/reassignManualCommands.test.ts
new file mode 100644
index 0000000000..f2feb6e711
--- /dev/null
+++ b/ambari-web/latest/src/Utils/reassignManualCommands.test.ts
@@ -0,0 +1,100 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import { describe, expect, it } from "vitest";
+import {
+ getDatabaseManualCommands,
+ getOozieJdbcDriver,
+ hasReassignManualCommands,
+ oozieUsesEmbeddedDatabase,
+} from "./reassignManualCommands";
+
+describe("Reassign manual commands", () => {
+ it("builds the classic embedded Oozie database copy sequence", () => {
+ const steps = getDatabaseManualCommands({
+ componentName: "OOZIE_SERVER",
+ groupName: "cluster-group",
+ sourceHost: "source1",
+ targetHost: "target1",
+ });
+
+ expect(steps).toHaveLength(4);
+ expect(steps?.[0]).toMatchObject({
+ description: expect.stringContaining("source1"),
+ command: "/hadoop/oozie/data/oozie-db",
+ });
+ expect(steps?.[1].description).toContain("target1");
+ expect(steps?.[3].command).toBe(
+ "chown -R oozie:cluster-group /hadoop/oozie/data"
+ );
+ });
+
+ it("builds the classic MySQL export and import sequence", () => {
+ const steps = getDatabaseManualCommands({
+ componentName: "MYSQL_SERVER",
+ sourceHost: "source1",
+ targetHost: "target1",
+ });
+
+ expect(steps?.map((step) => step.command).filter(Boolean)).toEqual([
+ "mysqldump db_name > backup-file.sql",
+ "CREATE DATABASE db_name;",
+ "mysql db_name < backup-file.sql",
+ ]);
+ });
+
+ it("recognizes only Derby as the Oozie embedded database", () => {
+ expect(oozieUsesEmbeddedDatabase("org.apache.derby.jdbc.EmbeddedDriver")).toBe(true);
+ expect(oozieUsesEmbeddedDatabase("com.mysql.jdbc.Driver")).toBe(false);
+ expect(oozieUsesEmbeddedDatabase(undefined)).toBe(false);
+ });
+
+ it("derives Oozie manual-step eligibility from the current config", () => {
+ const derbyResponse = {
+ items: [
+ {
+ configurations: [
+ {
+ type: "oozie-site",
+ properties: {
+ "oozie.service.JPAService.jdbc.driver":
+ "org.apache.derby.jdbc.EmbeddedDriver",
+ },
+ },
+ ],
+ },
+ ],
+ };
+ const driver = getOozieJdbcDriver(derbyResponse);
+
+ expect(driver).toBe("org.apache.derby.jdbc.EmbeddedDriver");
+ expect(hasReassignManualCommands("OOZIE_SERVER", driver)).toBe(true);
+ expect(
+ hasReassignManualCommands("OOZIE_SERVER", "com.mysql.jdbc.Driver")
+ ).toBe(false);
+ expect(hasReassignManualCommands("MYSQL_SERVER")).toBe(true);
+ expect(hasReassignManualCommands("RESOURCEMANAGER")).toBe(false);
+ });
+
+ it("treats a missing or malformed Oozie config as non-embedded", () => {
+ expect(getOozieJdbcDriver(undefined)).toBeUndefined();
+ expect(getOozieJdbcDriver({ items: [{ configurations: [] }] }))
+ .toBeUndefined();
+ expect(hasReassignManualCommands("OOZIE_SERVER", undefined)).toBe(false);
+ });
+});
diff --git a/ambari-web/latest/src/Utils/reassignManualCommands.ts b/ambari-web/latest/src/Utils/reassignManualCommands.ts
new file mode 100644
index 0000000000..938f5a7c63
--- /dev/null
+++ b/ambari-web/latest/src/Utils/reassignManualCommands.ts
@@ -0,0 +1,140 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+export type ReassignManualCommandStep = {
+ command?: string;
+ description: string;
+ number: number;
+};
+
+type DatabaseManualCommandOptions = {
+ componentName: string;
+ groupName?: string;
+ sourceHost?: string;
+ targetHost?: string;
+};
+
+export function getDatabaseManualCommands({
+ componentName,
+ groupName = "hadoop",
+ sourceHost = "",
+ targetHost = "",
+}: DatabaseManualCommandOptions): ReassignManualCommandStep[] | null {
+ if (componentName === "OOZIE_SERVER") {
+ return [
+ {
+ number: 1,
+ description: `On ${sourceHost}, copy the contents of the embedded Oozie database directory.`,
+ command: "/hadoop/oozie/data/oozie-db",
+ },
+ {
+ number: 2,
+ description: `Copy the directory to the target host ${targetHost}.`,
+ },
+ {
+ number: 3,
+ description: "Create the directory on the target host if it does not exist.",
+ command: "mkdir -p /hadoop/oozie/data/oozie-db",
+ },
+ {
+ number: 4,
+ description: "Update the Oozie data directory permissions.",
+ command: `chown -R oozie:${groupName} /hadoop/oozie/data`,
+ },
+ ];
+ }
+
+ if (componentName === "MYSQL_SERVER") {
+ return [
+ {
+ number: 1,
+ description: `On ${sourceHost}, export the MySQL metastore database.`,
+ command: "mysqldump db_name > backup-file.sql",
+ },
+ {
+ number: 2,
+ description: `Copy backup-file.sql to the target host ${targetHost}.`,
+ },
+ {
+ number: 3,
+ description: "Create the database on the target MySQL server.",
+ command: "CREATE DATABASE db_name;",
+ },
+ {
+ number: 4,
+ description: "Import the database backup on the target MySQL server.",
+ command: "mysql db_name < backup-file.sql",
+ },
+ ];
+ }
+
+ return null;
+}
+
+export function oozieUsesEmbeddedDatabase(driver: unknown): boolean {
+ return typeof driver === "string" && /derby/i.test(driver);
+}
+
+export function getOozieJdbcDriver(response: unknown): unknown {
+ if (!response || typeof response !== "object") {
+ return undefined;
+ }
+
+ const items = (response as { items?: unknown }).items;
+ if (!Array.isArray(items)) {
+ return undefined;
+ }
+
+ for (const item of items) {
+ if (!item || typeof item !== "object") {
+ continue;
+ }
+ const configurations = (item as { configurations?: unknown }).configurations;
+ if (!Array.isArray(configurations)) {
+ continue;
+ }
+ const oozieSite = configurations.find(
+ (configuration) =>
+ configuration &&
+ typeof configuration === "object" &&
+ (configuration as { type?: unknown }).type === "oozie-site"
+ ) as { properties?: Record<string, unknown> } | undefined;
+ if (oozieSite) {
+ return oozieSite.properties?.[
+ "oozie.service.JPAService.jdbc.driver"
+ ];
+ }
+ }
+
+ return undefined;
+}
+
+export function hasReassignManualCommands(
+ componentName: string | undefined,
+ oozieJdbcDriver?: unknown
+): boolean {
+ if (componentName === "OOZIE_SERVER") {
+ return oozieUsesEmbeddedDatabase(oozieJdbcDriver);
+ }
+ return [
+ "NAMENODE",
+ "SECONDARY_NAMENODE",
+ "MYSQL_SERVER",
+ "APP_TIMELINE_SERVER",
+ ].includes(componentName || "");
+}
diff --git a/ambari-web/latest/src/Utils/reassignValidation.test.ts b/ambari-web/latest/src/Utils/reassignValidation.test.ts
new file mode 100644
index 0000000000..395d62bfbb
--- /dev/null
+++ b/ambari-web/latest/src/Utils/reassignValidation.test.ts
@@ -0,0 +1,110 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import { describe, expect, it } from "vitest";
+import {
+ getReassignValidationErrors,
+ isMissingHostComponentError,
+} from "./reassignValidation";
+
+const stack = (reassignAllowed = true) => ({
+ items: [
+ {
+ StackServices: { service_name: "HDFS" },
+ components: [
+ {
+ StackServiceComponents: {
+ component_name: "NAMENODE",
+ reassign_allowed: reassignAllowed,
+ },
+ },
+ ],
+ },
+ ],
+});
+
+const model = (hosts: string[]) => ({
+ masterComponents: [
+ {
+ componentName: "NAMENODE",
+ hostComponents: hosts.map((host_name) => ({
+ HostRoles: { host_name },
+ })),
+ },
+ ],
+});
+
+describe("reassign entry validation", () => {
+ it("allows an installed reassignable component with a free target host", () => {
+ expect(
+ getReassignValidationErrors({
+ componentName: "NAMENODE",
+ serviceName: "HDFS",
+ allHostNames: ["host1", "host2"],
+ serviceComponentInfo: stack(),
+ serviceModel: model(["host1"]),
+ })
+ ).toEqual([]);
+ });
+
+ it("rejects one-host clusters and components occupying every host", () => {
+ expect(
+ getReassignValidationErrors({
+ componentName: "NAMENODE",
+ serviceName: "HDFS",
+ allHostNames: ["host1"],
+ serviceComponentInfo: stack(),
+ serviceModel: model(["host1"]),
+ })
+ ).toEqual([
+ "You must have at least 2 hosts to run the Move Wizard.",
+ "Every cluster host already has NAMENODE.",
+ ]);
+ });
+
+ it("rejects a direct route for a component the stack cannot reassign", () => {
+ expect(
+ getReassignValidationErrors({
+ componentName: "NAMENODE",
+ serviceName: "HDFS",
+ allHostNames: ["host1", "host2"],
+ serviceComponentInfo: stack(false),
+ serviceModel: model(["host1"]),
+ })
+ ).toContain("NAMENODE cannot be reassigned for HDFS.");
+ });
+});
+
+describe("reassign rollback recovery", () => {
+ it("treats an already deleted target component as idempotent", () => {
+ expect(isMissingHostComponentError({ response: { status: 404 } })).toBe(
+ true
+ );
+ expect(
+ isMissingHostComponentError({
+ response: { data: { message: "NoSuchResourceException" } },
+ })
+ ).toBe(true);
+ });
+
+ it("preserves unrelated rollback failures", () => {
+ expect(isMissingHostComponentError({ response: { status: 500 } })).toBe(
+ false
+ );
+ });
+});
diff --git a/ambari-web/latest/src/Utils/reassignValidation.ts b/ambari-web/latest/src/Utils/reassignValidation.ts
new file mode 100644
index 0000000000..c70544cc2b
--- /dev/null
+++ b/ambari-web/latest/src/Utils/reassignValidation.ts
@@ -0,0 +1,120 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import { get } from "lodash";
+
+type HostComponent = {
+ HostRoles?: { host_name?: string };
+ hostName?: string;
+};
+
+type InstalledComponent = {
+ componentName?: string;
+ hostComponents?: HostComponent[];
+};
+
+type ServiceModel = {
+ masterComponents?: InstalledComponent[];
+};
+
+type StackComponent = {
+ StackServiceComponents?: {
+ component_name?: string;
+ reassign_allowed?: boolean;
+ };
+};
+
+type StackService = {
+ StackServices?: { service_name?: string };
+ StackService?: { service_name?: string };
+ components?: StackComponent[];
+};
+
+type ServiceComponentInfo = {
+ items?: StackService[];
+};
+
+export const getComponentHostNames = (
+ component?: InstalledComponent
+): string[] =>
+ (component?.hostComponents || [])
+ .map((hostComponent) =>
+ get(hostComponent, "HostRoles.host_name", hostComponent.hostName)
+ )
+ .filter((hostName): hostName is string => Boolean(hostName));
+
+export const isMissingHostComponentError = (error: unknown) => {
+ const status = get(error, "response.status");
+ const message = String(
+ get(error, "response.data.message", get(error, "response.data", ""))
+ );
+ return status === 404 || message.includes("NoSuchResourceException");
+};
+
+export const getReassignValidationErrors = ({
+ componentName,
+ serviceName,
+ allHostNames,
+ serviceComponentInfo,
+ serviceModel,
+}: {
+ componentName?: string;
+ serviceName: string;
+ allHostNames: string[];
+ serviceComponentInfo: ServiceComponentInfo;
+ serviceModel: ServiceModel;
+}) => {
+ const errors: string[] = [];
+ if (!componentName) {
+ return ["No component was selected for reassignment."];
+ }
+ if (allHostNames.length < 2) {
+ errors.push("You must have at least 2 hosts to run the Move Wizard.");
+ }
+
+ const stackService = (serviceComponentInfo?.items || []).find(
+ (item) =>
+ get(item, "StackServices.service_name") === serviceName ||
+ get(item, "StackService.service_name") === serviceName
+ );
+ const stackComponent = (stackService?.components || []).find(
+ (component) =>
+ get(component, "StackServiceComponents.component_name") === componentName
+ );
+ if (!stackComponent ||
+ get(stackComponent, "StackServiceComponents.reassign_allowed") !== true) {
+ errors.push(`${componentName} cannot be reassigned for ${serviceName}.`);
+ }
+
+ const installedComponent = (serviceModel?.masterComponents || []).find(
+ (component) => component.componentName === componentName
+ );
+ if (!installedComponent) {
+ errors.push(`${componentName} is not installed for ${serviceName}.`);
+ } else {
+ const occupiedHosts = new Set(getComponentHostNames(installedComponent));
+ if (
+ allHostNames.length > 0 &&
+ allHostNames.every((hostName) => occupiedHosts.has(hostName))
+ ) {
+ errors.push(`Every cluster host already has ${componentName}.`);
+ }
+ }
+
+ return [...new Set(errors)];
+};
diff --git a/ambari-web/latest/src/Utils/serviceGlobalActions.test.ts b/ambari-web/latest/src/Utils/serviceGlobalActions.test.ts
new file mode 100644
index 0000000000..30a11fa984
--- /dev/null
+++ b/ambari-web/latest/src/Utils/serviceGlobalActions.test.ts
@@ -0,0 +1,51 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({ clusterRequests: vi.fn() }));
+vi.mock("../api/hostsApi", () => ({
+ HostsApi: { clusterRequests: mocks.clusterRequests },
+}));
+
+import { restartAllRequired } from "./taskUtils";
+
+describe("global service actions", () => {
+ beforeEach(() => {
+ mocks.clusterRequests.mockReset();
+ mocks.clusterRequests.mockResolvedValue({});
+ });
+
+ it("restarts only stale host components with the classic predicate", async () => {
+ await restartAllRequired("c1");
+
+ expect(mocks.clusterRequests).toHaveBeenCalledWith("c1", {
+ RequestInfo: {
+ command: "RESTART",
+ context: "Restart all required services",
+ operation_level: "host_component",
+ },
+ "Requests/resource_filters": [
+ {
+ hosts_predicate:
+ "HostRoles/stale_configs=true&HostRoles/cluster_name=c1",
+ },
+ ],
+ });
+ });
+});
diff --git a/ambari-web/latest/src/Utils/serviceNavigation.test.ts b/ambari-web/latest/src/Utils/serviceNavigation.test.ts
new file mode 100644
index 0000000000..7b0356d226
--- /dev/null
+++ b/ambari-web/latest/src/Utils/serviceNavigation.test.ts
@@ -0,0 +1,73 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import { describe, expect, it } from "vitest";
+import { resolveServiceNavigation } from "./serviceNavigation";
+
+const options = {
+ availableTabs: {
+ HDFS: ["summary", "configs"],
+ YARN: ["summary", "configs"],
+ },
+ canViewConfigs: true,
+ installedServices: ["HDFS", "YARN"],
+};
+
+describe("service navigation", () => {
+ it("returns an invalid service route to the first installed service", () => {
+ expect(
+ resolveServiceNavigation({
+ ...options,
+ requestedService: "REMOVED",
+ requestedTab: "configs",
+ })
+ ).toEqual({
+ redirectPath: "/main/services/HDFS/summary",
+ selectedService: "HDFS",
+ selectedTab: "summary",
+ });
+ });
+
+ it("keeps a valid service and tab selection", () => {
+ expect(
+ resolveServiceNavigation({
+ ...options,
+ requestedService: "YARN",
+ requestedTab: "configs",
+ })
+ ).toEqual({ selectedService: "YARN", selectedTab: "configs" });
+ });
+
+ it("converges invalid and unauthorized tabs to Summary", () => {
+ expect(
+ resolveServiceNavigation({
+ ...options,
+ requestedService: "HDFS",
+ requestedTab: "unknown",
+ }).redirectPath
+ ).toBe("/main/services/HDFS/summary");
+ expect(
+ resolveServiceNavigation({
+ ...options,
+ canViewConfigs: false,
+ requestedService: "HDFS",
+ requestedTab: "configs",
+ }).redirectPath
+ ).toBe("/main/services/HDFS/summary");
+ });
+});
diff --git a/ambari-web/latest/src/Utils/serviceNavigation.ts b/ambari-web/latest/src/Utils/serviceNavigation.ts
new file mode 100644
index 0000000000..afff60b167
--- /dev/null
+++ b/ambari-web/latest/src/Utils/serviceNavigation.ts
@@ -0,0 +1,69 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+type ServiceNavigationOptions = {
+ availableTabs: Record<string, string[]>;
+ canViewConfigs: boolean;
+ installedServices: string[];
+ requestedService?: string;
+ requestedTab?: string;
+};
+
+export function resolveServiceNavigation({
+ availableTabs,
+ canViewConfigs,
+ installedServices,
+ requestedService,
+ requestedTab,
+}: ServiceNavigationOptions): {
+ redirectPath?: string;
+ selectedService?: string;
+ selectedTab: string;
+} {
+ const selectedService =
+ requestedService && installedServices.includes(requestedService)
+ ? requestedService
+ : installedServices[0];
+ if (!selectedService) {
+ return { selectedTab: "summary" };
+ }
+
+ if (selectedService !== requestedService) {
+ return {
+ redirectPath: `/main/services/${selectedService}/summary`,
+ selectedService,
+ selectedTab: "summary",
+ };
+ }
+
+ const supportedTabs =
+ availableTabs[selectedService.toUpperCase()] || ["summary", "configs"];
+ const canSelectRequestedTab =
+ Boolean(requestedTab) &&
+ supportedTabs.includes(requestedTab as string) &&
+ (requestedTab !== "configs" || canViewConfigs);
+ const selectedTab = canSelectRequestedTab ? requestedTab as string : "summary";
+
+ return {
+ ...(selectedTab !== requestedTab && {
+ redirectPath: `/main/services/${selectedService}/${selectedTab}`,
+ }),
+ selectedService,
+ selectedTab,
+ };
+}
diff --git a/ambari-web/latest/src/api/quicklinksApi.ts b/ambari-web/latest/src/Utils/servicePermissions.ts
similarity index 63%
copy from ambari-web/latest/src/api/quicklinksApi.ts
copy to ambari-web/latest/src/Utils/servicePermissions.ts
index c97d482776..5a07a0b697 100644
--- a/ambari-web/latest/src/api/quicklinksApi.ts
+++ b/ambari-web/latest/src/Utils/servicePermissions.ts
@@ -16,15 +16,12 @@
* limitations under the License.
*/
-import { ambariApi } from "./config/axiosConfig";
-
-export const QuicklinksApi = {
- getQuicklinks: async (stackVersion: string,stackName:string, serviceName: string) => {
- const url = `/stacks/${stackName}/versions/${stackVersion}/services/${serviceName}/quicklinks?QuickLinkInfo/default=true&fields=*&_=${Date.now()}'`;
- const response = await ambariApi.request({
- url: url,
- method: "GET",
- });
- return response;
- }
-}
\ No newline at end of file
+export const canManageServices = ({
+ authorized,
+ featureEnabled,
+ wizardIsNotFinished,
+}: {
+ authorized: boolean;
+ featureEnabled: boolean;
+ wizardIsNotFinished: boolean;
+}) => authorized && featureEnabled && !wizardIsNotFinished;
diff --git a/ambari-web/latest/src/Utils/servicesConfigsPolicy.test.ts b/ambari-web/latest/src/Utils/servicesConfigsPolicy.test.ts
new file mode 100644
index 0000000000..f59fa7afd7
--- /dev/null
+++ b/ambari-web/latest/src/Utils/servicesConfigsPolicy.test.ts
@@ -0,0 +1,79 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({ postPersistData: vi.fn() }));
+vi.mock("../api/clusterApi", () => ({
+ default: { postPersistData: mocks.postPersistData },
+}));
+
+import {
+ buildClearedAddServiceState,
+ clearAddServiceWizardState,
+} from "./addServicePersistence";
+import { canManageServices } from "./servicePermissions";
+
+describe("services and configs policy", () => {
+ beforeEach(() => {
+ mocks.postPersistData.mockReset();
+ mocks.postPersistData.mockResolvedValue({});
+ });
+
+ it("requires authorization, the feature flag, and no conflicting wizard", () => {
+ expect(
+ canManageServices({
+ authorized: true,
+ featureEnabled: true,
+ wizardIsNotFinished: false,
+ })
+ ).toBe(true);
+ expect(
+ canManageServices({
+ authorized: false,
+ featureEnabled: true,
+ wizardIsNotFinished: false,
+ })
+ ).toBe(false);
+ expect(
+ canManageServices({
+ authorized: true,
+ featureEnabled: false,
+ wizardIsNotFinished: false,
+ })
+ ).toBe(false);
+ expect(
+ canManageServices({
+ authorized: true,
+ featureEnabled: true,
+ wizardIsNotFinished: true,
+ })
+ ).toBe(false);
+ });
+
+ it("clears only Add Service and cluster progress persistence", async () => {
+ const payload = buildClearedAddServiceState({ addServiceSteps: {} }, 7);
+ expect(JSON.parse(payload)).toEqual({
+ ADD_SERVICE: JSON.stringify({ addServiceSteps: {}, requestSequence: 7 }),
+ CLUSTER_STATE: JSON.stringify({}),
+ });
+
+ await clearAddServiceWizardState({ addServiceSteps: {} }, 7);
+ expect(mocks.postPersistData).toHaveBeenCalledWith(payload);
+ });
+});
diff --git a/ambari-web/latest/src/Utils/sslProtocolUtils.test.ts b/ambari-web/latest/src/Utils/sslProtocolUtils.test.ts
new file mode 100644
index 0000000000..cb6d36ac06
--- /dev/null
+++ b/ambari-web/latest/src/Utils/sslProtocolUtils.test.ts
@@ -0,0 +1,76 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import { describe, expect, it } from "vitest";
+import { getServiceProtocol, setProtocol } from "./sslProtocolUtils";
+
+const configurations = [
+ {
+ type: "hdfs-site",
+ properties: {
+ "dfs.http.policy": "HTTPS_ONLY",
+ enabled: "true",
+ present: "value",
+ },
+ },
+];
+
+describe("quick link protocol policy", () => {
+ it("honors explicit HTTP-only and HTTPS-only descriptor policies", () => {
+ expect(setProtocol(configurations, { type: "HTTP_ONLY" })).toBe("http");
+ expect(setProtocol([], { type: "HTTPS_ONLY" })).toBe("https");
+ });
+
+ it("uses Hadoop SSL when the descriptor has no protocol policy", () => {
+ expect(getServiceProtocol("HBASE", configurations)).toBe("https");
+ expect(getServiceProtocol("HBASE", [])).toBe("http");
+ });
+
+ it("supports exact, existence, and non-existence checks", () => {
+ expect(
+ setProtocol(configurations, {
+ type: "HTTPS",
+ checks: [
+ { site: "hdfs-site", property: "enabled", desired: "true" },
+ { site: "hdfs-site", property: "present", desired: "EXIST" },
+ { site: "hdfs-site", property: "missing", desired: "NOT_EXIST" },
+ ],
+ })
+ ).toBe("https");
+ });
+
+ it("reverses the preferred protocol when any check fails", () => {
+ expect(
+ setProtocol(configurations, {
+ type: "HTTPS",
+ checks: [
+ { site: "hdfs-site", property: "enabled", desired: "true" },
+ { site: "missing-site", property: "missing", desired: "EXIST" },
+ ],
+ })
+ ).toBe("http");
+ expect(
+ setProtocol(configurations, {
+ type: "HTTP",
+ checks: [
+ { site: "hdfs-site", property: "enabled", desired: "false" },
+ ],
+ })
+ ).toBe("https");
+ });
+});
diff --git a/ambari-web/latest/src/Utils/sslProtocolUtils.ts b/ambari-web/latest/src/Utils/sslProtocolUtils.ts
index a34d89c991..3d5768c34c 100644
--- a/ambari-web/latest/src/Utils/sslProtocolUtils.ts
+++ b/ambari-web/latest/src/Utils/sslProtocolUtils.ts
@@ -266,22 +266,9 @@ export const serviceSupportsHttps = (serviceName: string): boolean => {
* Following Ember.js service-specific protocol logic
*/
export const getServiceProtocol = (
- serviceName: string,
+ _serviceName: string,
configProperties: ConfigProperty[],
protocolConfig?: ProtocolConfig
): string => {
- const serviceConfig = getServiceSSLConfig(serviceName);
-
- if (!serviceConfig) {
- // Fallback to global SSL detection
- return setProtocol(configProperties, protocolConfig);
- }
-
- // If service doesn't support HTTPS, always return HTTP
- if (!serviceConfig.supportsHttps) {
- return 'http';
- }
-
- // Use Ember.js setProtocol logic for services that support HTTPS
return setProtocol(configProperties, protocolConfig);
};
diff --git a/ambari-web/latest/src/api/configsApi.ts b/ambari-web/latest/src/api/configsApi.ts
index f1b1afac81..2838e3674f 100644
--- a/ambari-web/latest/src/api/configsApi.ts
+++ b/ambari-web/latest/src/api/configsApi.ts
@@ -88,7 +88,7 @@ const ConfigsApi = {
version1: string,
version2: string
) {
- const url = `clusters/${clusterName}/configurations/service_config_versions?(service_name=${serviceName}&service_config_version.in(${version1},${version2}))`;
+ const url = `clusters/${clusterName}/configurations/service_config_versions?(service_name=${serviceName}%26service_config_version.in(${version1},${version2}))`;
const response = await ambariApi.request({
url: url,
method: "GET",
@@ -237,7 +237,7 @@ const ConfigsApi = {
getDesiredConfigsInfo: async (
clusterName: string
): Promise<AxiosResponse> => {
- const url = `/clusters/${clusterName}?fields=Clusters/desired_configs&_=${Date.now()}\``;
+ const url = `/clusters/${clusterName}?fields=Clusters/desired_configs&_=${Date.now()}`;
const response = await ambariApi.request({
url,
method: "GET",
diff --git a/ambari-web/latest/src/api/quicklinksApi.ts b/ambari-web/latest/src/api/quicklinksApi.ts
index c97d482776..99f82e07d4 100644
--- a/ambari-web/latest/src/api/quicklinksApi.ts
+++ b/ambari-web/latest/src/api/quicklinksApi.ts
@@ -20,11 +20,20 @@ import { ambariApi } from "./config/axiosConfig";
export const QuicklinksApi = {
getQuicklinks: async (stackVersion: string,stackName:string, serviceName: string) => {
- const url = `/stacks/${stackName}/versions/${stackVersion}/services/${serviceName}/quicklinks?QuickLinkInfo/default=true&fields=*&_=${Date.now()}'`;
+ const url = `/stacks/${stackName}/versions/${stackVersion}/services/${serviceName}/quicklinks?QuickLinkInfo/default=true&fields=*&_=${Date.now()}`;
const response = await ambariApi.request({
url: url,
method: "GET",
});
return response;
- }
-}
\ No newline at end of file
+ },
+ getPublicHostNames: async (clusterName: string, hostNames: string[]) => {
+ const hosts = hostNames.map(encodeURIComponent).join(",");
+ const url = `/clusters/${clusterName}/hosts?Hosts/host_name.in(${hosts})&fields=Hosts/public_host_name&minimal_response=true`;
+ const response = await ambariApi.request({
+ url,
+ method: "GET",
+ });
+ return response.data;
+ },
+};
diff --git a/ambari-web/latest/src/api/serviceApi.ts b/ambari-web/latest/src/api/serviceApi.ts
index e297196183..b9525e5305 100644
--- a/ambari-web/latest/src/api/serviceApi.ts
+++ b/ambari-web/latest/src/api/serviceApi.ts
@@ -77,19 +77,56 @@ export const ServiceApi = {
return response;
},
- createComponent:async function(clusterName:string,serviceName:string,componentName:string){
- const url=`/clusters/${clusterName}/services?ServiceInfo/service_name=${serviceName}`;
- const response=await ambariApi.request({
+ updateFlumeAgent: async function (
+ clusterName: string,
+ hostName: string,
+ agentName: string,
+ state: "STARTED" | "INSTALLED",
+ context: string
+ ) {
+ return ambariApi.request({
+ url: `/clusters/${clusterName}/hosts/${hostName}/host_components/FLUME_HANDLER`,
+ method: "PUT",
+ data: {
+ RequestInfo: {
+ context,
+ flume_handler: agentName,
+ operation_level: {
+ level: "HOST_COMPONENT",
+ cluster_name: clusterName,
+ service_name: "FLUME",
+ host_name: hostName,
+ },
+ },
+ Body: {
+ HostRoles: {
+ state,
+ },
+ },
+ },
+ });
+ },
+
+ createComponent: async function (
+ clusterName: string,
+ serviceName: string,
+ componentName: string
+ ) {
+ const url = `/clusters/${clusterName}/services?ServiceInfo/service_name=${serviceName}`;
+ const response = await ambariApi.request({
url,
- data:{
- components:[{
- ServiceComponentInfo:{
- component_name:componentName
- }
- }]
- }
- })
- return response.data
+ method: "POST",
+ data: {
+ components: [
+ {
+ ServiceComponentInfo: {
+ component_name: componentName,
+ },
+ },
+ ],
+ },
+ });
+ return response.data;
},
updateService: async function (
@@ -128,7 +165,7 @@ export const ServiceApi = {
},
getAllServiceComponentsListAndInitialMetrics: async (clusterName: string, fields: string) => {
- const url = `clusters/${clusterName}/components/?fields=${fields}&_=${Date.now()}\``
+ const url = `/clusters/${clusterName}/components?fields=${fields}&_=${Date.now()}`;
const response = await ambariApi.request({url: url,
method: "GET",
});
diff --git a/ambari-web/latest/src/api/serviceConfigApi.ts b/ambari-web/latest/src/api/serviceConfigApi.ts
index a66adcd0fd..fffe4526e4 100644
--- a/ambari-web/latest/src/api/serviceConfigApi.ts
+++ b/ambari-web/latest/src/api/serviceConfigApi.ts
@@ -26,13 +26,13 @@ export const ServiceConfigApi = {
});
return response;
},
- setIsCurrent: async function (clusterName: string, selectedServices: string[]) {
+ getCurrentServiceConfigs: async function (clusterName: string, selectedServices: string[]) {
const servicesQuery = selectedServices.join(',');
- const url = `/clusters/${clusterName}/configurations/service_config_versions?service_name.in(${servicesQuery})&is_current=true&fields=*&_=${Date.now()}\`;`
+ const url = `/clusters/${clusterName}/configurations/service_config_versions?service_name.in(${servicesQuery})&is_current=true&fields=*&_=${Date.now()}`;
const response = await ambariApi.request({
url: url,
method: "GET",
});
return response;
},
-};
\ No newline at end of file
+};
diff --git a/ambari-web/latest/src/api/servicesConfigsApi.test.ts b/ambari-web/latest/src/api/servicesConfigsApi.test.ts
new file mode 100644
index 0000000000..71e95269b8
--- /dev/null
+++ b/ambari-web/latest/src/api/servicesConfigsApi.test.ts
@@ -0,0 +1,136 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({ request: vi.fn() }));
+vi.mock("./config/axiosConfig", () => ({
+ ambariApi: { request: mocks.request },
+ supressErrorAmbariApi: { request: mocks.request },
+}));
+
+import ConfigsApi from "./configsApi";
+import { ActionsApi } from "./actionsApi";
+import { QuicklinksApi } from "./quicklinksApi";
+import { ServiceApi } from "./serviceApi";
+import { ServiceConfigApi } from "./serviceConfigApi";
+
+describe("services and configs API contracts", () => {
+ beforeEach(() => {
+ mocks.request.mockReset();
+ mocks.request.mockResolvedValue({ data: {} });
+ vi.spyOn(Date, "now").mockReturnValue(1234);
+ });
+
+ it("creates a component with the classic services collection POST", async () => {
+ await ServiceApi.createComponent("c1", "HIVE", "HIVE_SERVER");
+ expect(mocks.request).toHaveBeenCalledWith({
+ url: "/clusters/c1/services?ServiceInfo/service_name=HIVE",
+ method: "POST",
+ data: {
+ components: [
+ { ServiceComponentInfo: { component_name: "HIVE_SERVER" } },
+ ],
+ },
+ });
+ });
+
+ it("targets a Flume handler by agent and host", async () => {
+ await ServiceApi.updateFlumeAgent(
+ "c1",
+ "host1",
+ "agent1",
+ "STARTED",
+ "Start Flume Agent agent1"
+ );
+ expect(mocks.request).toHaveBeenCalledWith({
+ url: "/clusters/c1/hosts/host1/host_components/FLUME_HANDLER",
+ method: "PUT",
+ data: {
+ RequestInfo: {
+ context: "Start Flume Agent agent1",
+ flume_handler: "agent1",
+ operation_level: {
+ level: "HOST_COMPONENT",
+ cluster_name: "c1",
+ service_name: "FLUME",
+ host_name: "host1",
+ },
+ },
+ Body: { HostRoles: { state: "STARTED" } },
+ },
+ });
+ });
+
+ it("updates service maintenance with the classic service PUT", async () => {
+ await ActionsApi.turnOnOffMaintenance("c1", "HDFS", {
+ requestInfo: "Turn On Maintenance Mode for HDFS",
+ passive_state: "ON",
+ });
+ expect(mocks.request).toHaveBeenCalledWith({
+ url: "/clusters/c1/services/HDFS",
+ method: "PUT",
+ data: {
+ RequestInfo: { context: "Turn On Maintenance Mode for HDFS" },
+ Body: { ServiceInfo: { maintenance_state: "ON" } },
+ },
+ });
+ });
+
+ it("uses exact non-metrics component and desired-config URLs", async () => {
+ await ServiceApi.getAllServiceComponentsListAndInitialMetrics("c1", "a,b");
+ await ConfigsApi.getDesiredConfigsInfo("c1");
+ expect(mocks.request).toHaveBeenNthCalledWith(1, {
+ url: "/clusters/c1/components?fields=a,b&_=1234",
+ method: "GET",
+ });
+ expect(mocks.request).toHaveBeenNthCalledWith(2, {
+ url: "/clusters/c1?fields=Clusters/desired_configs&_=1234",
+ method: "GET",
+ });
+ });
+
+ it("preserves Ambari's encoded grouped version predicate", async () => {
+ await ConfigsApi.getMultipleVersionConfigValues("c1", "HDFS", "1", "2");
+ expect(mocks.request).toHaveBeenCalledWith({
+ url: "clusters/c1/configurations/service_config_versions?(service_name=HDFS%26service_config_version.in(1,2))",
+ method: "GET",
+ });
+ });
+
+ it("loads descriptors and public-host mappings without malformed suffixes", async () => {
+ await QuicklinksApi.getQuicklinks("3.2.0", "BIGTOP", "HDFS");
+ await QuicklinksApi.getPublicHostNames("c1", ["host/one", "host2"]);
+ expect(mocks.request).toHaveBeenNthCalledWith(1, {
+ url: "/stacks/BIGTOP/versions/3.2.0/services/HDFS/quicklinks?QuickLinkInfo/default=true&fields=*&_=1234",
+ method: "GET",
+ });
+ expect(mocks.request).toHaveBeenNthCalledWith(2, {
+ url: "/clusters/c1/hosts?Hosts/host_name.in(host%2Fone,host2)&fields=Hosts/public_host_name&minimal_response=true",
+ method: "GET",
+ });
+ });
+
+ it("reloads current versions for the installed service list", async () => {
+ await ServiceConfigApi.getCurrentServiceConfigs("c1", ["HDFS", "YARN"]);
+ expect(mocks.request).toHaveBeenCalledWith({
+ url: "/clusters/c1/configurations/service_config_versions?service_name.in(HDFS,YARN)&is_current=true&fields=*&_=1234",
+ method: "GET",
+ });
+ });
+});
diff --git a/ambari-web/latest/src/components/ServiceOperationRouteGuard.test.tsx b/ambari-web/latest/src/components/ServiceOperationRouteGuard.test.tsx
new file mode 100644
index 0000000000..789339bbce
--- /dev/null
+++ b/ambari-web/latest/src/components/ServiceOperationRouteGuard.test.tsx
@@ -0,0 +1,64 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import { render, screen } from "@testing-library/react";
+import { ComponentProps } from "react";
+import { MemoryRouter, Route, Routes } from "react-router-dom";
+import { describe, expect, it } from "vitest";
+import { AppContext } from "../store/context";
+import ServiceOperationRouteGuard from "./ServiceOperationRouteGuard";
+
+const renderGuard = (wizardIsNotFinished: boolean) =>
+ render(
+ <AppContext.Provider
+ value={
+ { wizardIsNotFinished } as unknown as ComponentProps<
+ typeof AppContext.Provider
+ >["value"]
+ }
+ >
+ <MemoryRouter initialEntries={["/operation"]}>
+ <Routes>
+ <Route
+ path="/operation"
+ element={
+ <ServiceOperationRouteGuard>
+ <div>Operation Wizard</div>
+ </ServiceOperationRouteGuard>
+ }
+ />
+ <Route
+ path="/main/dashboard/metrics"
+ element={<div>Cluster Dashboard</div>}
+ />
+ </Routes>
+ </MemoryRouter>
+ </AppContext.Provider>
+ );
+
+describe("service operation route guard", () => {
+ it("allows the route when no upgrade or other user's wizard is active", () => {
+ renderGuard(false);
+ expect(screen.getByText("Operation Wizard")).toBeTruthy();
+ });
+
+ it("redirects a conflicting wizard route", () => {
+ renderGuard(true);
+ expect(screen.getByText("Cluster Dashboard")).toBeTruthy();
+ });
+});
diff --git a/ambari-web/latest/src/api/quicklinksApi.ts b/ambari-web/latest/src/components/ServiceOperationRouteGuard.tsx
similarity index 63%
copy from ambari-web/latest/src/api/quicklinksApi.ts
copy to ambari-web/latest/src/components/ServiceOperationRouteGuard.tsx
index c97d482776..eacdd71da8 100644
--- a/ambari-web/latest/src/api/quicklinksApi.ts
+++ b/ambari-web/latest/src/components/ServiceOperationRouteGuard.tsx
@@ -16,15 +16,20 @@
* limitations under the License.
*/
-import { ambariApi } from "./config/axiosConfig";
+import { ReactNode, useContext } from "react";
+import { Navigate } from "react-router-dom";
+import { AppContext } from "../store/context";
-export const QuicklinksApi = {
- getQuicklinks: async (stackVersion: string,stackName:string, serviceName: string) => {
- const url = `/stacks/${stackName}/versions/${stackVersion}/services/${serviceName}/quicklinks?QuickLinkInfo/default=true&fields=*&_=${Date.now()}'`;
- const response = await ambariApi.request({
- url: url,
- method: "GET",
- });
- return response;
- }
-}
\ No newline at end of file
+export default function ServiceOperationRouteGuard({
+ children,
+}: {
+ children: ReactNode;
+}) {
+ const { wizardIsNotFinished } = useContext(AppContext);
+
+ return wizardIsNotFinished ? (
+ <Navigate to="/main/dashboard/metrics" replace />
+ ) : (
+ children
+ );
+}
diff --git a/ambari-web/latest/src/components/Sidebar/RunAllServiceCheck.tsx b/ambari-web/latest/src/components/Sidebar/RunAllServiceCheck.tsx
index 90b9f085ca..580222171e 100644
--- a/ambari-web/latest/src/components/Sidebar/RunAllServiceCheck.tsx
+++ b/ambari-web/latest/src/components/Sidebar/RunAllServiceCheck.tsx
@@ -37,12 +37,7 @@ const RunAllServiceCheck = () => {
const [showConfirmation, setShowConfirmation] = useState(false);
const [isRunning, setIsRunning] = useState(false);
- // Check authorization - requires SERVICE.RUN_CUSTOM_COMMAND, SERVICE.RUN_SERVICE_CHECK, SERVICE.TOGGLE_MAINTENANCE, or SERVICE.ENABLE_HA
- const canRunServiceCheck =
- hasAuthorization("SERVICE.RUN_CUSTOM_COMMAND") ||
- hasAuthorization("SERVICE.RUN_SERVICE_CHECK") ||
- hasAuthorization("SERVICE.TOGGLE_MAINTENANCE") ||
- hasAuthorization("SERVICE.ENABLE_HA");
+ const canRunServiceCheck = hasAuthorization("SERVICE.RUN_SERVICE_CHECK");
// Block during active upgrade (not suspended)
const isUpgradeBlocking = upgradeIsRunning && !upgradeSuspended;
@@ -224,4 +219,4 @@ const RunAllServiceCheck = () => {
);
};
-export default RunAllServiceCheck;
\ No newline at end of file
+export default RunAllServiceCheck;
diff --git a/ambari-web/latest/src/components/Sidebar/SidebarItem.tsx b/ambari-web/latest/src/components/Sidebar/SidebarItem.tsx
index f13db30b7c..76eb9be5bc 100644
--- a/ambari-web/latest/src/components/Sidebar/SidebarItem.tsx
+++ b/ambari-web/latest/src/components/Sidebar/SidebarItem.tsx
@@ -42,6 +42,9 @@ import modalManager from "../../store/ModalManager";
import { useAuth } from "../../hooks/useAuth";
import { serviceNameModelMapping } from "../../constants";
import RunAllServiceCheck from "./RunAllServiceCheck";
+import { checkNnLastCheckpointTime } from "../../screens/Hosts/actions";
+import { get } from "lodash";
+import { canManageServices } from "../../Utils/servicePermissions";
// interface SidebarElement {
// id: string;
@@ -62,6 +65,17 @@ interface SidebarItemProps {
hasChildren?: boolean;
}
+type NameNodeHostComponent = {
+ HostRoles?: { host_name?: string; state?: string };
+ hostName?: string;
+ state?: string;
+};
+
+type NameNodeComponent = {
+ componentName?: string;
+ hostComponents?: NameNodeHostComponent[];
+};
+
const SidebarItem = ({
ele,
onClick,
@@ -75,6 +89,9 @@ const SidebarItem = ({
upgradeIsRunning,
upgradeSuspended,
services: contextServices,
+ supports,
+ wizardIsNotFinished,
+ runningOperationsCount,
} = useContext(AppContext);
const { allServiceModels } = useContext(ServiceContext);
const location = useLocation();
@@ -107,42 +124,30 @@ const SidebarItem = ({
let hasStoppedServices = false;
let hasStartedServices = false;
let hasServicesRequiringRestart = false;
- let totalServices = 0;
- let startedServicesCount = 0;
- let stoppedServicesCount = 0;
-
contextServices.forEach((service: any) => {
const serviceName = service.ServiceInfo?.service_name;
- const serviceState =
- allServiceModels?.[serviceNameModelMapping[serviceName]]?.serviceState;
+ const serviceModel =
+ allServiceModels?.[serviceNameModelMapping[serviceName]];
+ const serviceState = serviceModel?.serviceState;
+ const healthStatus = serviceModel?.healthStatus;
- // Count total services (excluding client-only services for start/stop operations)
- const isClientOnlyService = allServiceModels?.[serviceNameModelMapping[serviceName]]?.isClientOnlyService;
- if (!isClientOnlyService) {
- totalServices++;
- }
+ const isClientOnlyService = serviceModel?.isClientOnlyService;
// Following Ember.js logic: check for red status (stopped/installed services)
// Ember: stoppedServices = content.filter(_service => _service.get('healthStatus') === 'red')
- if (
- serviceState === "INSTALLED" ||
- serviceState === "INIT" ||
- serviceState === "INSTALL_FAILED" ||
- serviceState === "STOPPED"
- ) {
+ if (!isClientOnlyService && (healthStatus === "red" ||
+ serviceState === "INSTALLED" ||
+ serviceState === "INIT" ||
+ serviceState === "INSTALL_FAILED" ||
+ serviceState === "STOPPED")) {
hasStoppedServices = true;
- if (!isClientOnlyService) {
- stoppedServicesCount++;
- }
}
// Following Ember.js logic: check for green status (started services)
// Ember: !content.someProperty('healthStatus', 'green')
- if (serviceState === "STARTED") {
+ if (!isClientOnlyService &&
+ (healthStatus === "green" || serviceState === "STARTED")) {
hasStartedServices = true;
- if (!isClientOnlyService) {
- startedServicesCount++;
- }
}
if (allServiceModels?.[serviceNameModelMapping[serviceName]]?.isRestartRequiredForService) {
@@ -150,30 +155,104 @@ const SidebarItem = ({
}
});
- // Check if ALL non-client-only services are started
- const allServicesStarted = totalServices > 0 && startedServicesCount === totalServices;
-
- // Check if ALL non-client-only services are stopped
- const allServicesStopped = totalServices > 0 && stoppedServicesCount === totalServices;
-
return {
hasStoppedServices,
hasStartedServices,
hasServicesRequiringRestart,
- allServicesStarted,
- allServicesStopped,
};
};
const {
+ hasStoppedServices,
+ hasStartedServices,
hasServicesRequiringRestart,
- allServicesStarted,
- allServicesStopped,
} = getServiceStates();
- // Check if user has any service operation permissions and upgrade is not blocking
+ const canAddService = canManageServices({
+ authorized: canAddDeleteServices,
+ featureEnabled: supports.enableAddDeleteServices,
+ wizardIsNotFinished,
+ });
+ const isStartStopBusy = runningOperationsCount > 0;
+
const hasAnyServiceOperationPermissions =
- (canAddDeleteServices || canStartStopServices) && !isUpgradeBlocking;
+ (canAddDeleteServices || canStartStopServices) &&
+ !isUpgradeBlocking;
+
+ const executeAllServicesAction = async (
+ label: string,
+ action: () => Promise<unknown>
+ ) => {
+ try {
+ await action();
+ showBackgroundModal();
+ } catch (error) {
+ const message = get(
+ error,
+ "response.data.message",
+ get(error, "message", `${label} could not be submitted.`)
+ );
+ modalManager.show({
+ modalTitle: `${label} Failed`,
+ modalBody: message,
+ successCallback: () => {
+ modalManager.hide();
+ void executeAllServicesAction(label, action);
+ },
+ onClose: () => modalManager.hide(),
+ options: { okButtonText: "RETRY" },
+ });
+ }
+ };
+
+ const confirmAllServicesAction = (
+ label: string,
+ message: string,
+ action: () => Promise<unknown>
+ ) => {
+ modalManager.show({
+ modalTitle: "Confirmation",
+ modalBody: message,
+ successCallback: () => {
+ modalManager.hide();
+ void executeAllServicesAction(label, action);
+ },
+ onClose: () => modalManager.hide(),
+ options: { okButtonText: `CONFIRM ${label.toUpperCase()}` },
+ });
+ };
+
+ const confirmStopAllServices = () => {
+ const showConfirmation = () =>
+ confirmAllServicesAction(
+ "Stop All",
+ "You are about to stop all services.",
+ () => stopAllServices(clusterName)
+ );
+ const hdfsMasterComponents = get(
+ allServiceModels,
+ "hdfs.masterComponents",
+ []
+ ) as NameNodeComponent[];
+ const nameNodeHost = hdfsMasterComponents
+ .find((component) => component.componentName === "NAMENODE")
+ ?.hostComponents?.find(
+ (hostComponent) =>
+ get(hostComponent, "HostRoles.state", hostComponent.state) ===
+ "STARTED"
+ );
+ const hostName = get(
+ nameNodeHost,
+ "HostRoles.host_name",
+ nameNodeHost?.hostName
+ );
+
+ if (hostName) {
+ void checkNnLastCheckpointTime(showConfirmation, hostName, clusterName);
+ } else {
+ showConfirmation();
+ }
+ };
const handleClick = (e: React.MouseEvent<HTMLDivElement>) => {
// If this is the Cluster Admin item and it's currently closed, navigate to the first admin route
// Only navigate when opening the menu, not when closing it, and only if not already on an admin page
@@ -227,8 +306,7 @@ const SidebarItem = ({
/>
}
>
- {/* Add Service - Requires SERVICE.ADD_DELETE_SERVICES authorization and no upgrade blocking */}
- {canAddDeleteServices && !isUpgradeBlocking && (
+ {canAddService && (
<Dropdown.Item
onClick={() => {
navigate("/main/service/add/step1");
@@ -239,14 +317,16 @@ const SidebarItem = ({
</Dropdown.Item>
)}
- {/* Start All - Disabled when all services are started (TLHASD-997 fix) */}
{canStartStopServices && (
<Dropdown.Item
- disabled={allServicesStarted}
- onClick={async () => {
- if (!allServicesStarted) {
- await startAllServices(clusterName);
- showBackgroundModal();
+ disabled={!hasStoppedServices || isStartStopBusy}
+ onClick={() => {
+ if (hasStoppedServices && !isStartStopBusy) {
+ confirmAllServicesAction(
+ "Start All",
+ "You are about to start all services.",
+ () => startAllServices(clusterName)
+ );
}
}}
>
@@ -255,14 +335,12 @@ const SidebarItem = ({
</Dropdown.Item>
)}
- {/* Stop All - Disabled when all services are stopped (TLHASD-997 consistency fix) */}
{canStartStopServices && (
<Dropdown.Item
- disabled={allServicesStopped}
- onClick={async () => {
- if (!allServicesStopped) {
- await stopAllServices(clusterName);
- showBackgroundModal();
+ disabled={!hasStartedServices || isStartStopBusy}
+ onClick={() => {
+ if (hasStartedServices && !isStartStopBusy) {
+ confirmStopAllServices();
}
}}
>
@@ -275,16 +353,18 @@ const SidebarItem = ({
{canStartStopServices && (
<Dropdown.Item
disabled={!hasServicesRequiringRestart}
- onClick={async () => {
+ onClick={() => {
if (hasServicesRequiringRestart) {
modalManager.show({
modalTitle: "Confirmation",
modalBody:
"This will trigger alerts as the service is restarted. To suppress alerts, turn on Maintenance Mode for services listed above prior to running Restart All Required",
- successCallback: async () => {
+ successCallback: () => {
modalManager.hide();
- await restartAllRequired(clusterName);
- showBackgroundModal();
+ void executeAllServicesAction(
+ "Restart All Required",
+ () => restartAllRequired(clusterName)
+ );
},
onClose: () => {
modalManager.hide();
diff --git a/ambari-web/latest/src/hooks/useConfigSaver.test.tsx b/ambari-web/latest/src/hooks/useConfigSaver.test.tsx
new file mode 100644
index 0000000000..f79f6f9960
--- /dev/null
+++ b/ambari-web/latest/src/hooks/useConfigSaver.test.tsx
@@ -0,0 +1,170 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import { act, renderHook } from "@testing-library/react";
+import { ComponentProps, ReactNode } from "react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { ConfigPropertiesType } from "../screens/CommonConfigs/types";
+
+const mocks = vi.hoisted(() => ({
+ saveConfigs: vi.fn(),
+ updateConfigGroupProperties: vi.fn(),
+ showModal: vi.fn(),
+}));
+vi.mock("../api/configsApi", () => ({
+ default: {
+ saveConfigs: mocks.saveConfigs,
+ updateConfigGroupProperties: mocks.updateConfigGroupProperties,
+ },
+}));
+vi.mock("../store/ModalManager", () => ({
+ default: { show: mocks.showModal, hide: vi.fn() },
+}));
+
+import { useConfigSaver } from "./useConfigSaver";
+import { AppContext } from "../store/context";
+
+const property = (name: string, value: string, previousValue: string) => ({
+ propertyName: name,
+ propertyDisplayname: name,
+ propertyValue: value,
+ propertyAttributes: { type: "text" },
+ fileName: "hdfs-site.xml",
+ value,
+ previousValue,
+ final: "false",
+ savedFinal: "false",
+ isEditable: true,
+ foundInPropertyValues: true,
+ isRequiredByAgent: true,
+ propertyType: ["TEXT"],
+});
+
+const configProperties: ConfigPropertiesType = {
+ HDFS: {
+ "Advanced hdfs-site": {
+ errors: 0,
+ properties: {
+ changed: property("changed", "new", "old"),
+ unchanged: property("unchanged", "keep", "keep"),
+ deleted: {
+ ...property("deleted", "old", "old"),
+ value: null,
+ isVisible: false,
+ },
+ },
+ },
+ },
+};
+
+const wrapper = ({ children }: { children: ReactNode }) => (
+ <AppContext.Provider
+ value={
+ {
+ clusterName: "c1",
+ services: [{ ServiceInfo: { service_name: "HDFS" } }],
+ } as unknown as ComponentProps<typeof AppContext.Provider>["value"]
+ }
+ >
+ {children}
+ </AppContext.Provider>
+);
+
+describe("configuration save lifecycle", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("keeps saving state until the full replacement payload settles", async () => {
+ let resolveSave!: (value: unknown) => void;
+ mocks.saveConfigs.mockReturnValue(
+ new Promise((resolve) => {
+ resolveSave = resolve;
+ })
+ );
+ const setSubmitDisabled = vi.fn();
+ const { result } = renderHook(
+ () =>
+ useConfigSaver(
+ false,
+ setSubmitDisabled,
+ "Default",
+ configProperties,
+ "HDFS",
+ [],
+ "Module 04 save"
+ ),
+ { wrapper }
+ );
+
+ let saveResult!: Promise<boolean>;
+ act(() => {
+ saveResult = result.current.saveStepConfigs();
+ });
+ expect(result.current.saveInProgress).toBe(true);
+ expect(setSubmitDisabled).toHaveBeenCalledWith(true);
+
+ await act(async () => {
+ resolveSave({});
+ expect(await saveResult).toBe(true);
+ });
+
+ expect(result.current.saveInProgress).toBe(false);
+ expect(setSubmitDisabled).toHaveBeenLastCalledWith(false);
+ expect(mocks.saveConfigs).toHaveBeenCalledWith("c1", [
+ {
+ Clusters: {
+ desired_config: [
+ expect.objectContaining({
+ type: "hdfs-site",
+ properties: { changed: "new", unchanged: "keep" },
+ properties_attributes: expect.objectContaining({
+ text: { changed: "true", unchanged: "true" },
+ }),
+ }),
+ ],
+ },
+ },
+ ]);
+ });
+
+ it("returns false and restores the submit state after a rejected save", async () => {
+ mocks.saveConfigs.mockRejectedValue(new Error("save failed"));
+ const setSubmitDisabled = vi.fn();
+ const { result } = renderHook(
+ () =>
+ useConfigSaver(
+ false,
+ setSubmitDisabled,
+ "Default",
+ configProperties,
+ "HDFS",
+ [],
+ "Module 04 save"
+ ),
+ { wrapper }
+ );
+
+ await act(async () => {
+ expect(await result.current.saveStepConfigs()).toBe(false);
+ });
+ expect(result.current.saveInProgress).toBe(false);
+ expect(setSubmitDisabled).toHaveBeenLastCalledWith(false);
+ expect(mocks.showModal).toHaveBeenCalled();
+ });
+});
diff --git a/ambari-web/latest/src/hooks/useConfigSaver.tsx b/ambari-web/latest/src/hooks/useConfigSaver.tsx
index 38d9941d7a..60db9dc4d1 100644
--- a/ambari-web/latest/src/hooks/useConfigSaver.tsx
+++ b/ambari-web/latest/src/hooks/useConfigSaver.tsx
@@ -51,7 +51,6 @@ export const useConfigSaver = (
serviceConfigVersionNote: string
) => {
const [saveInProgress, setSaveInProgress] = useState(false);
- const [saveConfigsFlag, setSaveConfigsFlag] = useState(true);
const heapsizeException = [
"hadoop_heapsize",
@@ -80,28 +79,30 @@ export const useConfigSaver = (
const serviceNames = services.map((service: any) => service.ServiceInfo?.service_name) || [];
- const saveStepConfigs = () => {
+ const saveStepConfigs = async () => {
if (!isSubmitDisabled) {
- // startSave();
- // showWarningPopupsBeforeSave();
- saveConfigs();
+ return saveConfigs();
}
+ return false;
};
- const saveConfigs = async () => {
+ const saveConfigs = async (): Promise<boolean> => {
startSave();
try {
if (selectedConfigGroup === "Default") {
- saveConfigsForDefaultGroup();
+ await saveConfigsForDefaultGroup();
} else {
- saveConfigsForNonDefaultGroup();
+ await saveConfigsForNonDefaultGroup();
}
+ return true;
+ } catch {
+ return false;
} finally {
completeSave();
}
};
- const saveConfigsForNonDefaultGroup = () => {
+ const saveConfigsForNonDefaultGroup = async () => {
if (selectedConfigGroup && selectedConfigGroup !== "Default") {
const overriddenConfigs = getConfigsForGroup(
configProperties,
@@ -112,7 +113,7 @@ export const useConfigSaver = (
!isEmpty(overriddenConfigs) &&
isOverriddenConfigsModified(overriddenConfigs)
) {
- saveGroup(overriddenConfigs);
+ await saveGroup(overriddenConfigs);
} else {
putConfigGroupChangesSuccess();
}
@@ -131,7 +132,7 @@ export const useConfigSaver = (
return hasChangedConfigs;
};
- const saveConfigsForDefaultGroup = () => {
+ const saveConfigsForDefaultGroup = async () => {
let data: any = [];
Object.keys(configProperties).map((serviceName: string) => {
var serviceConfigs = getServiceConfigToSave(
@@ -144,9 +145,9 @@ export const useConfigSaver = (
});
if (data.length) {
- putChangedConfigurations(data);
+ await putChangedConfigurations(data);
} else {
- onDoPutClusterConfigurations();
+ onDoPutClusterConfigurations(true);
}
};
@@ -426,8 +427,9 @@ export const useConfigSaver = (
}
if (
- Object.keys(attributes.final).length ||
- Object.keys(attributes.password).length
+ Object.values(attributes).some(
+ (attributeValues) => Object.keys(attributeValues).length > 0
+ )
) {
desired_config.properties_attributes = attributes;
}
@@ -477,13 +479,14 @@ export const useConfigSaver = (
const addM = (name: string, value: string) => {
return (
+ typeof value === "string" &&
heapsizeRegExp.test(name) &&
!heapsizeException.includes(name) &&
!value.endsWith("m")
);
};
- const saveGroup = (overriddenConfigs: PropertyType[]) => {
+ const saveGroup = async (overriddenConfigs: PropertyType[]) => {
const fileNamesToSave = [...new Set(
overriddenConfigs
.map(config => config.fileName)
@@ -498,8 +501,9 @@ export const useConfigSaver = (
const groupId = get(configGroup, 'ConfigGroup.id');
if (!groupId) {
- console.error('Config group ID not found');
- return;
+ const error = new Error("Config group ID not found");
+ doPUTClusterConfigurationSiteErrorCallback();
+ throw error;
}
// Prepare the configs specifically for this config group
@@ -510,7 +514,7 @@ export const useConfigSaver = (
// For non-default groups, we need to use the override value for this specific group
value: (config.overrideValues || []).find(
(ov: any) => ov.groupName === selectedConfigGroup
- )?.value || config.value
+ )?.value ?? config.value
};
});
@@ -533,7 +537,7 @@ export const useConfigSaver = (
};
groupData.ConfigGroup.id = groupId;
- updateConfigGroup(groupData);
+ await updateConfigGroup(groupData);
};
// const createConfigGroup = () => {
@@ -569,24 +573,25 @@ export const useConfigSaver = (
};
const putConfigGroupChangesSuccess = () => {
- setSaveConfigsFlag(true);
- onDoPutClusterConfigurations();
+ onDoPutClusterConfigurations(true);
};
const doPUTClusterConfigurationSiteSuccessCallback = () => {
let doConfigActions = true;
- onDoPutClusterConfigurations(doConfigActions);
+ onDoPutClusterConfigurations(true, doConfigActions);
};
const doPUTClusterConfigurationSiteErrorCallback = () => {
- setSaveConfigsFlag(false);
- onDoPutClusterConfigurations();
+ onDoPutClusterConfigurations(false);
};
- const onDoPutClusterConfigurations = (doConfigActions?: boolean) => {
+ const onDoPutClusterConfigurations = (
+ isSuccess: boolean,
+ doConfigActions?: boolean
+ ) => {
let status = "unknown";
let result = {
- flag: saveConfigsFlag,
+ flag: isSuccess,
message: "",
value: "",
};
diff --git a/ambari-web/latest/src/hooks/useLazyQuicklinks.ts b/ambari-web/latest/src/hooks/useLazyQuicklinks.ts
index c2465b2a86..c9226e3f42 100644
--- a/ambari-web/latest/src/hooks/useLazyQuicklinks.ts
+++ b/ambari-web/latest/src/hooks/useLazyQuicklinks.ts
@@ -27,6 +27,22 @@ import {
setProtocol,
getServiceProtocol,
} from "../Utils/sslProtocolUtils";
+import { useAuth } from "./useAuth";
+import {
+ createPublicHostNameMap,
+ QuicklinkConfiguration,
+ resolveQuicklinkConfigPlaceholders,
+ substituteQuicklinkTemplate,
+} from "../Utils/quicklinks";
+
+type QuicklinkHostComponent = {
+ HostRoles?: { host_name?: string; state?: string };
+};
+
+type QuicklinkComponentInfo = {
+ ServiceComponentInfo?: { component_name?: string };
+ host_components?: QuicklinkHostComponent[];
+};
/**
* Lazy-loading quicklinks hook following Ember.js pattern
@@ -41,11 +57,13 @@ import {
export const useLazyQuicklinks = (serviceName: string) => {
const { clusterName, cluster, isClusterInstalled } = useContext(AppContext);
const { polledHostComponentsData, allServiceModels } = useContext(ServiceContext);
+ const { user } = useAuth();
const [quicklinks, setQuicklinks] = useState<any>([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const currentServiceRef = useRef<string>(serviceName);
+ const publicHostNamesRef = useRef(new Map<string, string>());
// Memoized hostname extraction
const memoizedGetHostName = useCallback(
@@ -173,52 +191,42 @@ export const useLazyQuicklinks = (serviceName: string) => {
}
}
+ if (serviceName.toUpperCase() === "MAPREDUCE2" && link.port) {
+ const configuredHostProperty = link.port[`${protocol}_config`];
+ const configuredHostSite = configProperties.find(
+ (conf: QuicklinkConfiguration) => conf.type === link.port.site
+ );
+ const configuredHostAndPort =
+ configuredHostSite?.properties?.[configuredHostProperty];
+ const configuredHost = configuredHostAndPort?.match(
+ /([\w\d.-]+):(\d+)/
+ )?.[1];
+ if (configuredHost) {
+ host = configuredHost;
+ }
+ }
+
+ host = publicHostNamesRef.current.get(host) || host;
+
// Handle port configuration with regex
if (link.port) {
port = extractPortWithRegex(link.port, protocol, configProperties);
}
- // Replace URL template placeholders following Ember.js pattern
- if (link.requires_user_name === "true") {
- // This would need user name - for now we'll use empty string
- finalUrl = finalUrl.replace(/%@/g, (match: string, index: number) => {
- switch (index) {
- case 0:
- return protocol;
- case 1:
- return host;
- case 2:
- return port;
- case 3:
- return ""; // username placeholder
- default:
- return match;
- }
- });
- } else {
- // Replace placeholders: protocol, host, port
- let replacementIndex = 0;
- finalUrl = finalUrl.replace(/%@/g, () => {
- switch (replacementIndex++) {
- case 0:
- return protocol;
- case 1:
- return host;
- case 2:
- return port;
- default:
- return "";
- }
- });
- }
-
-
- return finalUrl;
+ finalUrl = substituteQuicklinkTemplate(
+ finalUrl,
+ protocol,
+ host,
+ port,
+ user?.user_name || "",
+ link.requires_user_name === "true"
+ );
+ return resolveQuicklinkConfigPlaceholders(finalUrl, configProperties);
} catch (error) {
return link.url;
}
},
- [extractPortWithRegex, parseHostFromUri, serviceName]
+ [extractPortWithRegex, parseHostFromUri, serviceName, user?.user_name]
);
// Check if any quicklinks have overridden host configuration (following Ember.js hasOverriddenHost pattern)
@@ -1139,9 +1147,10 @@ export const useLazyQuicklinks = (serviceName: string) => {
}
const processedLinks: any[] = [];
+ publicHostNamesRef.current = new Map();
// Get component information for all services (following Ember.js isRelatedComponentInstalled pattern)
- let allComponentInfo: any = null;
+ let allComponentInfo: QuicklinkComponentInfo[] | null = null;
try {
const componentFields = `ServiceComponentInfo/service_name,ServiceComponentInfo/component_name,ServiceComponentInfo/total_count,host_components/HostRoles/host_name,host_components/HostRoles/state&minimal_response=true`;
const componentResponse =
@@ -1154,6 +1163,29 @@ export const useLazyQuicklinks = (serviceName: string) => {
// Will fallback to original logic if this fails
}
+ if (allComponentInfo) {
+ const hostNames = [
+ ...new Set<string>(
+ allComponentInfo.flatMap((component) =>
+ (component.host_components || [])
+ .map((hostComponent) =>
+ get(hostComponent, "HostRoles.host_name")
+ )
+ .filter((hostName): hostName is string => Boolean(hostName))
+ )
+ ),
+ ];
+ if (hostNames.length > 0) {
+ const publicHosts = await QuicklinksApi.getPublicHostNames(
+ clusterName,
+ hostNames
+ );
+ publicHostNamesRef.current = createPublicHostNameMap(
+ publicHosts.items || []
+ );
+ }
+ }
+
// Check service-specific HA status
let isHDFSHAEnabled = false;
let isYARNHAEnabled = false;
@@ -1870,7 +1902,6 @@ export const useLazyQuicklinks = (serviceName: string) => {
});
});
} else {
- // Non-HA processing with sophisticated SSL detection
links.forEach((link: any) => {
if (link.removed || !link.visible) {
return;
@@ -1878,24 +1909,44 @@ export const useLazyQuicklinks = (serviceName: string) => {
try {
- // Use sophisticated SSL detection for non-HA services
- const finalUrl = reconstructURL(
- link,
- configurations,
- undefined,
- protocolConfig
- );
- const hostName = memoizedGetHostName(finalUrl);
-
+ const relatedComponent = allComponentInfo
+ ? find(
+ allComponentInfo,
+ (item) =>
+ get(item, "ServiceComponentInfo.component_name") ===
+ link.component_name
+ )
+ : null;
+ const componentHosts = (relatedComponent?.host_components || [])
+ .filter(
+ (hostComponent) =>
+ serviceName.toUpperCase() !== "OOZIE" ||
+ get(hostComponent, "HostRoles.state") === "STARTED"
+ )
+ .map((hostComponent) =>
+ get(hostComponent, "HostRoles.host_name")
+ );
+ const hostsToRender =
+ link.host || !allComponentInfo ? [undefined] : componentHosts;
- if (finalUrl && hostName) {
- processedLinks.push({
- label: link.label,
- url: finalUrl,
- hostName: hostName,
- componentName: link.component_name,
- });
- }
+ hostsToRender.forEach((componentHost: string | undefined) => {
+ const finalUrl = reconstructURL(
+ link,
+ configurations,
+ componentHost,
+ protocolConfig
+ );
+ const hostName = memoizedGetHostName(finalUrl);
+
+ if (finalUrl && hostName) {
+ processedLinks.push({
+ label: link.label,
+ url: finalUrl,
+ hostName,
+ componentName: link.component_name,
+ });
+ }
+ });
} catch (error) {
if (serviceName.toUpperCase() === "PINOT") {
console.error("[PINOT DEBUG] Error processing link:", error);
@@ -1905,7 +1956,10 @@ export const useLazyQuicklinks = (serviceName: string) => {
}
});
- return processedLinks;
+ return processedLinks.map((link) => ({
+ ...link,
+ hostName: publicHostNamesRef.current.get(link.hostName) || link.hostName,
+ }));
},
[
serviceName,
diff --git a/ambari-web/latest/src/router/RoutesList.tsx b/ambari-web/latest/src/router/RoutesList.tsx
index 652ea41294..f6a13c8443 100644
--- a/ambari-web/latest/src/router/RoutesList.tsx
+++ b/ambari-web/latest/src/router/RoutesList.tsx
@@ -49,6 +49,7 @@ import AdminViewRedirect from "../screens/Authentication/AdminViewRedirect";
import Experimental from "../screens/Experimental";
import FeatureRouteGuard from "../components/FeatureRouteGuard";
import AdminViewRouteGuard from "../components/AdminViewRouteGuard";
+import ServiceOperationRouteGuard from "../components/ServiceOperationRouteGuard";
const RoutesList: RouteObject[] = [
{
@@ -100,7 +101,21 @@ const RoutesList: RouteObject[] = [
path: "main",
element: <MainLayout />,
children: [
- { path: "service/add/:stepNumber", element: <AddWizardUrlMapping /> },
+ {
+ path: "service/add/:stepNumber",
+ element: (
+ <FeatureRouteGuard feature="enableAddDeleteServices">
+ <ProtectedRoute
+ requireAuthorization="SERVICE.ADD_DELETE_SERVICES"
+ redirectTo="/main/dashboard/metrics"
+ >
+ <ServiceOperationRouteGuard>
+ <AddWizardUrlMapping />
+ </ServiceOperationRouteGuard>
+ </ProtectedRoute>
+ </FeatureRouteGuard>
+ ),
+ },
{
path: "dashboard",
element: <Outlet />,
@@ -123,21 +138,57 @@ const RoutesList: RouteObject[] = [
},
{
path: "highAvailability/:componentName/enable/:stepNumber",
- element: <ServiceLoader />,
+ element: (
+ <ProtectedRoute
+ requireAuthorization="SERVICE.ENABLE_HA"
+ redirectTo="/main/dashboard/metrics"
+ >
+ <ServiceOperationRouteGuard>
+ <ServiceLoader />
+ </ServiceOperationRouteGuard>
+ </ProtectedRoute>
+ ),
},
{
path: ":componentName/federation/:stepNumber",
- element: <ServiceLoader />,
+ element: (
+ <ProtectedRoute
+ requireAuthorization="SERVICE.ENABLE_HA"
+ redirectTo="/main/dashboard/metrics"
+ >
+ <ServiceOperationRouteGuard>
+ <ServiceLoader />
+ </ServiceOperationRouteGuard>
+ </ProtectedRoute>
+ ),
},
{
path: "highAvailability/:componentName/manage/:stepNumber",
- element: <ServiceLoader />,
+ element: (
+ <ProtectedRoute
+ requireAuthorization="SERVICE.ENABLE_HA"
+ redirectTo="/main/dashboard/metrics"
+ >
+ <ServiceOperationRouteGuard>
+ <ServiceLoader />
+ </ServiceOperationRouteGuard>
+ </ProtectedRoute>
+ ),
},
],
},
{
path: "service/reassign/:componentName/:stepNumber",
- element: <ServiceLoader />,
+ element: (
+ <ProtectedRoute
+ requireAuthorization="SERVICE.MOVE"
+ redirectTo="/main/dashboard/metrics"
+ >
+ <ServiceOperationRouteGuard>
+ <ServiceLoader />
+ </ServiceOperationRouteGuard>
+ </ProtectedRoute>
+ ),
},
{ path: "hosts", element: <HostsList /> },
{ path: "hosts/component/:componentName", element: <HostsList /> },
diff --git a/ambari-web/latest/src/screens/ClusterWizard/Step10.tsx b/ambari-web/latest/src/screens/ClusterWizard/Step10.tsx
index 72f191eed7..b6984b7972 100644
--- a/ambari-web/latest/src/screens/ClusterWizard/Step10.tsx
+++ b/ambari-web/latest/src/screens/ClusterWizard/Step10.tsx
@@ -313,17 +313,19 @@ function Step10({ wizardName = "clusterCreation" }: Step10Props) {
onNext={async () => {
const clusterName = getStepData("NAME", "clusterName");
- await ClusterApi.updateCluster(clusterName, {
- Clusters: {
- provisioning_state: "INSTALLED",
- },
- });
- if(wizardName==="clusterCreation"){
- await syncConfigGroupsToServer(clusterName, state);
+ if (wizardName === "clusterCreation") {
+ await ClusterApi.updateCluster(clusterName, {
+ Clusters: {
+ provisioning_state: "INSTALLED",
+ },
+ });
+ await syncConfigGroupsToServer(clusterName, state);
+ flushStateToDb("cancel");
+ window.location.href = "#/main/dashboard/metrics";
+ window.location.reload();
+ } else {
+ await flushStateToDb("cancel");
}
- flushStateToDb("cancel");
- window.location.href = "#/main/dashboard/metrics";
- window.location.reload();
}}
onCancel={() => {
flushStateToDb("cancel");
diff --git a/ambari-web/latest/src/screens/CommonConfigs/AdvancedConfigs.tsx b/ambari-web/latest/src/screens/CommonConfigs/AdvancedConfigs.tsx
index 629980e9b9..e7f4a74c19 100644
--- a/ambari-web/latest/src/screens/CommonConfigs/AdvancedConfigs.tsx
+++ b/ambari-web/latest/src/screens/CommonConfigs/AdvancedConfigs.tsx
@@ -46,12 +46,15 @@ import {
} from "./ConfigUtils";
import TestConnection from "./TestConnection";
import Modal from "../../components/Modal";
-import { configValidator } from "../../Utils/validators";
import useEnhancedConfigs from "../../hooks/useEnhancedConfigs";
import OverlayBackdrop from "../../components/OverlayBackdrop";
import { useAuth } from "../../hooks/useAuth";
import Tooltip from "../../components/Tooltip";
import { formatParamsForDisplay, formatParamsForSave, shouldUseMultilineFormatting } from "../../Utils/jvmFormatUtils";
+import {
+ parseCustomPropertyInput,
+ validateCustomPropertyKey,
+} from "../../Utils/customConfigProperties";
type AdvancedConfigsType = {
configPropertiesData: any;
@@ -555,54 +558,12 @@ function AdvancedConfigs({
};
const parseMultiPropertyInput = (input: string) => {
- const lines = input.split('\n').map(line => line.trim()).filter(line => line.length > 0);
- const properties: PropertyType[] = [];
- const errors: string[] = [];
- const seenKeys = new Set<string>();
-
- lines.forEach((line, index) => {
- const lineNumber = index + 1;
-
-
- if (!line.includes('=')) {
- errors.push(`Line ${lineNumber}: Invalid format. Expected key=value`);
- return;
- }
-
- const equalIndex = line.indexOf('=');
- const key = line.substring(0, equalIndex).trim();
- const value = line.substring(equalIndex + 1).trim();
-
-
- if (!key) {
- errors.push(`Line ${lineNumber}: Key cannot be empty`);
- return;
- }
-
- if (!configValidator.isValidConfigKey(key)) {
- errors.push(`Line ${lineNumber}: Invalid key "${key}". Only alphanumerics, hyphens, underscores, asterisks and periods are allowed.`);
- return;
- }
-
-
- if (seenKeys.has(key)) {
- errors.push(`Line ${lineNumber}: Duplicate key "${key}"`);
- return;
- }
-
-
- // Check if property exists and is visible (not removed)
- const existingProperty = advancedConfigs[chosenService][customPropertyType]?.properties?.[key];
- if (existingProperty && existingProperty.isVisible !== false && existingProperty.value !== null) {
- errors.push(`Line ${lineNumber}: Property "${key}" already exists`);
- return;
- }
-
- seenKeys.add(key);
-
-
- const propertyTypes = selectedPropertyTypes.length > 0 ? selectedPropertyTypes : ['TEXT'];
- const property: PropertyType = {
+ const existingProperties =
+ advancedConfigs[chosenService][customPropertyType]?.properties || {};
+ const parsed = parseCustomPropertyInput(input, existingProperties);
+ const propertyTypes =
+ selectedPropertyTypes.length > 0 ? selectedPropertyTypes : ["TEXT"];
+ const properties: PropertyType[] = parsed.properties.map(({ key, value }) => ({
propertyName: key,
propertyAttributes: {
type: getInputTypeFromPropertyType(propertyTypes),
@@ -615,12 +576,9 @@ function AdvancedConfigs({
fileName: customPropertyType.replace(/^Custom\s*/, "") + ".xml",
propertyType: propertyTypes,
isEditable: true,
- };
+ }));
- properties.push(property);
- });
-
- return { properties, errors };
+ return { properties, errors: parsed.errors };
};
const validateMultiPropertyInput = (input: string) => {
@@ -630,19 +588,10 @@ function AdvancedConfigs({
};
const validateSingleProperty = (property: PropertyType) => {
- const key = property.propertyName.trim();
- if (!key) {
- return "Property key is required";
- }
- if (!configValidator.isValidConfigKey(key)) {
- return "Invalid key. Only alphanumerics, hyphens, underscores, asterisks and periods are allowed.";
- }
- // Check if property exists and is visible (not removed)
- const existingProperty = advancedConfigs[chosenService][customPropertyType]?.properties?.[key];
- if (existingProperty && existingProperty.isVisible !== false && existingProperty.value !== null) {
- return `Property "${key}" already exists`;
- }
- return "";
+ return validateCustomPropertyKey(
+ property.propertyName,
+ advancedConfigs[chosenService][customPropertyType]?.properties || {}
+ );
};
const handleModeToggle = (multiMode: boolean) => {
@@ -695,13 +644,15 @@ function AdvancedConfigs({
if (newCustomProperty && newCustomProperty.propertyName.trim()) {
const advancedConfigsCopy = cloneDeep(advancedConfigs);
+ const propertyName = newCustomProperty.propertyName.trim();
if (!advancedConfigsCopy[chosenService][customPropertyType].properties) {
advancedConfigsCopy[chosenService][customPropertyType].properties = {};
}
advancedConfigsCopy[chosenService][customPropertyType].properties[
- newCustomProperty.propertyName
+ propertyName
] = {
...newCustomProperty,
+ propertyName,
// Mark as not found in original property values since it's a new custom property
foundInPropertyValues: false,
};
@@ -1318,22 +1269,11 @@ function AdvancedConfigs({
onChange={(e) => {
const newProperty = cloneDeep(newCustomProperty);
newProperty.propertyName = e.target.value;
- if (newProperty.propertyName === "") {
- newProperty.errorMessage = "This is required";
- } else if (
- !configValidator.isValidConfigKey(newProperty.propertyName)
- ) {
- newProperty.errorMessage =
- "Invalid Key. Only alphanumerics, hyphens, underscores, asterisks and periods are allowed.";
- } else {
- // Check if property exists and is visible (not removed)
- const existingProperty = advancedConfigs[chosenService][customPropertyType]?.properties?.[newProperty.propertyName.trim()];
- if (existingProperty && existingProperty.isVisible !== false && existingProperty.value !== null) {
- newProperty.errorMessage = `Property "${newProperty.propertyName}" already exists`;
- } else {
- newProperty.errorMessage = "";
- }
- }
+ newProperty.errorMessage = validateCustomPropertyKey(
+ newProperty.propertyName,
+ advancedConfigs[chosenService][customPropertyType]
+ ?.properties || {}
+ );
setNewCustomProperty(newProperty);
}}
/>
diff --git a/ambari-web/latest/src/screens/CommonConfigs/ChooseConfigGroup.tsx b/ambari-web/latest/src/screens/CommonConfigs/ChooseConfigGroup.tsx
index 77412828f2..fd227ec7de 100644
--- a/ambari-web/latest/src/screens/CommonConfigs/ChooseConfigGroup.tsx
+++ b/ambari-web/latest/src/screens/CommonConfigs/ChooseConfigGroup.tsx
@@ -82,7 +82,7 @@ export default function ChooseConfigGroup({
const { hasAuthorization } = useAuth();
// Check specific authorizations for config groups operations
- const canModifyConfigs = hasAuthorization('SERVICE.MODIFY_CONFIGS');
+ const canManageConfigGroups = hasAuthorization('SERVICE.MANAGE_CONFIG_GROUPS');
const manageConfigGroup = useMemo(
() => ({
@@ -109,11 +109,10 @@ export default function ChooseConfigGroup({
const allOptions = useMemo(
() => {
- // Only include "Manage Config Group" option if user has SERVICE.MODIFY_CONFIGS permission
const baseOptions = [defaultOption, ...options];
- return canModifyConfigs ? [manageConfigGroup, ...baseOptions] : baseOptions;
+ return canManageConfigGroups ? [manageConfigGroup, ...baseOptions] : baseOptions;
},
- [manageConfigGroup, defaultOption, options, canModifyConfigs]
+ [manageConfigGroup, defaultOption, options, canManageConfigGroups]
);
const fetchConfigGroups = async () => {
diff --git a/ambari-web/latest/src/screens/CommonConfigs/TestConnection.test.tsx b/ambari-web/latest/src/screens/CommonConfigs/TestConnection.test.tsx
new file mode 100644
index 0000000000..6f98c09706
--- /dev/null
+++ b/ambari-web/latest/src/screens/CommonConfigs/TestConnection.test.tsx
@@ -0,0 +1,235 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import {
+ act,
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { ComponentProps } from "react";
+import { ConfigPropertiesType } from "./types";
+
+const mocks = vi.hoisted(() => ({
+ createClusterCustomAction: vi.fn(),
+ createCustomAction: vi.fn(),
+ getTaskId: vi.fn(),
+ getTaskStatus: vi.fn(),
+ pausePolling: vi.fn(),
+ resumePolling: vi.fn(),
+ pollCallback: undefined as undefined | (() => Promise<void>),
+ usePolling: vi.fn(),
+}));
+vi.mock("../../api/clusterApi", () => ({
+ default: {
+ createClusterCustomAction: mocks.createClusterCustomAction,
+ createCustomAction: mocks.createCustomAction,
+ },
+}));
+vi.mock("../../api/requestApi", () => ({
+ RequestApi: {
+ getTaskId: mocks.getTaskId,
+ getTaskStatus: mocks.getTaskStatus,
+ },
+}));
+vi.mock("../../api/kerberosApi", () => ({
+ default: { testKdcConnection: vi.fn() },
+}));
+vi.mock("../../hooks/usePolling", () => ({
+ default: mocks.usePolling,
+}));
+
+import TestConnection from "./TestConnection";
+import { AppContext } from "../../store/context";
+
+const configProperty = (name: string, value: string | string[]) => ({
+ propertyName: name,
+ propertyDisplayname: name,
+ propertyValue: value,
+ propertyAttributes: {},
+ previousValue: value,
+ value,
+ final: "false",
+ isEditable: true,
+});
+
+const configProperties: ConfigPropertiesType = {
+ HIVE: {
+ "hive-site": {
+ errors: 0,
+ properties: {
+ "ambari.hive.db.schema.name": configProperty(
+ "ambari.hive.db.schema.name",
+ "hive"
+ ),
+ "javax.jdo.option.ConnectionUserName": configProperty(
+ "javax.jdo.option.ConnectionUserName",
+ "hive"
+ ),
+ "javax.jdo.option.ConnectionPassword": configProperty(
+ "javax.jdo.option.ConnectionPassword",
+ ""
+ ),
+ "javax.jdo.option.ConnectionDriverName": configProperty(
+ "javax.jdo.option.ConnectionDriverName",
+ "driver"
+ ),
+ "javax.jdo.option.ConnectionURL": configProperty(
+ "javax.jdo.option.ConnectionURL",
+ "jdbc:test"
+ ),
+ },
+ },
+ "hive-env": {
+ errors: 0,
+ properties: {
+ hive_database_type: configProperty(
+ "hive_database_type",
+ "POSTGRES"
+ ),
+ },
+ },
+ HIVE_METASTORE: {
+ errors: 0,
+ properties: {
+ hive_metastore_hosts: configProperty(
+ "hive_metastore_hosts",
+ ["host1"]
+ ),
+ },
+ },
+ },
+};
+
+const renderConnection = () =>
+ render(
+ <AppContext.Provider
+ value={
+ {
+ clusterName: "c1",
+ services: [{ ServiceInfo: { service_name: "HIVE" } }],
+ ambariProperties: {},
+ } as unknown as ComponentProps<typeof AppContext.Provider>["value"]
+ }
+ >
+ <TestConnection
+ buttonLabel="Test Connection"
+ serviceName="HIVE"
+ configProperties={configProperties}
+ />
+ </AppContext.Provider>
+ );
+
+describe("database test connection recovery", () => {
+ afterEach(cleanup);
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.pollCallback = undefined;
+ mocks.usePolling.mockImplementation((callback) => {
+ mocks.pollCallback = callback;
+ return {
+ pausePolling: mocks.pausePolling,
+ resumePolling: mocks.resumePolling,
+ };
+ });
+ });
+
+ it("leaves Connecting and permits retry when request creation fails", async () => {
+ mocks.createClusterCustomAction.mockRejectedValue(
+ new Error("request unavailable")
+ );
+ renderConnection();
+ const button = await screen.findByRole("button", {
+ name: "Test Connection",
+ });
+
+ fireEvent.click(button);
+ await screen.findByText("Connection Failed");
+ expect((button as HTMLButtonElement).disabled).toBe(false);
+ expect(mocks.pausePolling).toHaveBeenCalled();
+
+ fireEvent.click(button);
+ await waitFor(() =>
+ expect(mocks.createClusterCustomAction).toHaveBeenCalledTimes(2)
+ );
+ });
+
+ it("stops polling and permits retry when task polling fails", async () => {
+ mocks.createClusterCustomAction.mockResolvedValue({
+ Requests: { id: "17", status: "Accepted" },
+ });
+ mocks.getTaskId.mockResolvedValue({
+ items: [{ Tasks: { id: "3" } }],
+ });
+ mocks.getTaskStatus.mockRejectedValue(new Error("poll unavailable"));
+ renderConnection();
+ const button = await screen.findByRole("button", {
+ name: "Test Connection",
+ });
+
+ fireEvent.click(button);
+ await waitFor(() => expect(mocks.resumePolling).toHaveBeenCalled());
+ await act(async () => {
+ await mocks.pollCallback?.();
+ });
+
+ await screen.findByText("Connection Failed");
+ expect((button as HTMLButtonElement).disabled).toBe(false);
+ expect(mocks.pausePolling).toHaveBeenCalled();
+ });
+
+ it("reports a completed task with a failed DB check as failure", async () => {
+ mocks.createClusterCustomAction.mockResolvedValue({
+ Requests: { id: "17", status: "Accepted" },
+ });
+ mocks.getTaskId.mockResolvedValue({
+ items: [{ Tasks: { id: "3" } }],
+ });
+ mocks.getTaskStatus.mockResolvedValue({
+ Tasks: {
+ status: "COMPLETED",
+ stderr: "database rejected the connection",
+ stdout: "",
+ structured_out: {
+ db_connection_check: {
+ exit_code: 1,
+ message: "Invalid database credentials",
+ },
+ },
+ },
+ });
+ renderConnection();
+ const button = await screen.findByRole("button", {
+ name: "Test Connection",
+ });
+
+ fireEvent.click(button);
+ await waitFor(() => expect(mocks.resumePolling).toHaveBeenCalled());
+ await act(async () => {
+ await mocks.pollCallback?.();
+ });
+
+ await screen.findByText("Connection Failed");
+ expect((button as HTMLButtonElement).disabled).toBe(false);
+ expect(mocks.pausePolling).toHaveBeenCalled();
+ });
+});
diff --git a/ambari-web/latest/src/screens/CommonConfigs/TestConnection.tsx b/ambari-web/latest/src/screens/CommonConfigs/TestConnection.tsx
index b4feb18bb9..93aff6bf50 100644
--- a/ambari-web/latest/src/screens/CommonConfigs/TestConnection.tsx
+++ b/ambari-web/latest/src/screens/CommonConfigs/TestConnection.tsx
@@ -166,23 +166,54 @@ export default function TestConnection({
const { services, ambariProperties, clusterName } = useContext(AppContext);
+ const failConnection = (error: unknown, fallbackMessage: string) => {
+ const message = get(error, "response.data.message", get(error, "message", fallbackMessage));
+ setTaskID(null);
+ setRequestId(null);
+ pausePolling();
+ setIsConnecting(false);
+ setIsConnectionSuccessful(false);
+ setErrorMessage({
+ error_log: "Connection Test Failed",
+ stderr: message || fallbackMessage,
+ output_log: "Connection test did not complete",
+ stdout: "Retry the connection test after resolving the reported error.",
+ });
+ };
+
const getTaskStatus = async () => {
- if (requestId !== null && taskID !== null) {
+ if (requestId === null || taskID === null) {
+ return;
+ }
+
+ try {
const response = await RequestApi.getTaskStatus(requestId, taskID);
updateTaskStatus(response);
- } else {
- console.warn("requestId or taskID is null");
+ } catch (error) {
+ failConnection(error, "Unable to read the connection test task status.");
}
};
const updateTaskStatus = (response: any) => {
const status = get(response, "Tasks.status", null);
if (status) {
if (status === "COMPLETED") {
+ const structuredOut = get(
+ response,
+ "Tasks.structured_out.db_connection_check"
+ );
setTaskID(null);
setRequestId(null);
pausePolling();
setIsConnecting(false);
- setIsConnectionSuccessful(true);
+ if (structuredOut && Number(structuredOut.exit_code) !== 0) {
+ setIsConnectionSuccessful(false);
+ setErrorMessage({
+ ...get(response, "Tasks", {}),
+ structuredOut: structuredOut.message,
+ });
+ } else {
+ setIsConnectionSuccessful(true);
+ }
} else if (status === "FAILED" || status === "ABORTED" || status === "TIMEDOUT") {
setTaskID(null);
setRequestId(null);
@@ -193,19 +224,21 @@ export default function TestConnection({
} else {
console.log("Task is still in progress, current status:", status);
}
+ } else {
+ failConnection(response, "The connection test task has no status.");
}
};
const { pausePolling, resumePolling } = usePolling(getTaskStatus, 1000);
useEffect(() => {
pausePolling();
- }, []);
+ }, [pausePolling]);
useEffect(() => {
if (taskID && requestId) {
resumePolling();
}
- }, [taskID]);
+ }, [taskID, requestId, resumePolling]);
const installedServicesInCluster = services.map(
(service) => service.ServiceInfo.service_name
@@ -436,41 +469,61 @@ export default function TestConnection({
);
if (response) {
if (response.Requests.status === "Accepted") {
- onCreateActionSuccess(response);
+ await onCreateActionSuccess(response);
+ } else {
+ failConnection(response, "The connection test request was not accepted.");
}
+ } else {
+ failConnection(response, "The connection test request returned no response.");
}
} catch (error) {
- setIsConnectionSuccessful(false);
console.error("Error creating cluster custom action");
+ failConnection(error, "Unable to create the connection test request.");
}
} else {
try {
const response = await ClusterApi.createCustomAction(payload);
if (response) {
if (response.Requests.status === "Accepted") {
- onCreateActionSuccess(response);
+ await onCreateActionSuccess(response);
+ } else {
+ failConnection(response, "The connection test request was not accepted.");
}
+ } else {
+ failConnection(response, "The connection test request returned no response.");
}
} catch (error) {
console.log(
"Error creating custom action for service not installed",
error
);
- setIsConnectionSuccessful(false);
+ failConnection(error, "Unable to create the connection test request.");
}
}
};
const onCreateActionSuccess = async (response: any) => {
const requestId = response.Requests.id;
- if (requestId) {
- setRequestId(requestId);
+ if (!requestId) {
+ failConnection(response, "The connection test response did not include a request ID.");
+ return;
+ }
+
+ setRequestId(requestId);
+ try {
const requestResponse = await RequestApi.getTaskId(requestId);
const taskIdFromResponse = get(requestResponse, "items.0.Tasks.id", null);
- if (taskIdFromResponse) {
- setTaskID(taskIdFromResponse);
+ if (!taskIdFromResponse) {
+ failConnection(
+ requestResponse,
+ "The connection test request did not include a task ID."
+ );
+ return;
}
+ setTaskID(taskIdFromResponse);
+ } catch (error) {
+ failConnection(error, "Unable to load the connection test task.");
}
};
@@ -500,6 +553,9 @@ export default function TestConnection({
};
const handleButtonClick = () => {
+ setErrorMessage(null);
+ setIsConnectionSuccessful(false);
+ setShowErrorMessage(false);
if (serviceName === "KERBEROS") {
testKDCConnection();
} else {
diff --git a/ambari-web/latest/src/screens/ConfigGroups/ManageConfigGroups.tsx b/ambari-web/latest/src/screens/ConfigGroups/ManageConfigGroups.tsx
index 983743c6c4..d4a1bbd404 100644
--- a/ambari-web/latest/src/screens/ConfigGroups/ManageConfigGroups.tsx
+++ b/ambari-web/latest/src/screens/ConfigGroups/ManageConfigGroups.tsx
@@ -45,6 +45,11 @@ import ConfigGroupApi from "../../api/configGroupApi";
import { ActionTypes } from "../ClusterWizard/clusterStore/types";
import { useAuth } from "../../hooks/useAuth";
import classNames from "classnames";
+import {
+ buildConfigGroupUpdatePlan,
+ moveHostsToConfigGroup,
+ removeConfigGroupAndReturnHosts,
+} from "../../Utils/configGroupSavePlan";
type ManageConfigGroupsProps = {
isOpen: boolean;
@@ -85,17 +90,18 @@ export default function ManageConfigGroups({
const [showSelectConfigHostsModal, setShowSelectConfigHostsModal] =
useState(false);
const [enableSave, setEnableSave] = useState(false);
+ const [saving, setSaving] = useState(false);
+ const [saveError, setSaveError] = useState("");
const { state, dispatch } = useContext(ClusterCreationContext);
// Authorization hooks - implementing Ember.js config groups authorization patterns
const { hasAuthorization } = useAuth();
- // Check specific authorizations for config groups operations
- // Based on Ember.js canEdit logic: App.isAuthorized('SERVICE.MODIFY_CONFIGS')
- const canModifyConfigs = hasAuthorization("SERVICE.MODIFY_CONFIGS");
+ const canManageConfigGroups = hasAuthorization("SERVICE.MANAGE_CONFIG_GROUPS");
const isRenameConfigGroup = useRef(false);
+ const isDuplicateConfigGroup = useRef(false);
const config = useRef({
name: "",
description: "",
@@ -357,18 +363,6 @@ export default function ManageConfigGroups({
);
};
- const removeConfigGroup = (configGroupName: string) => {
- let newConfigGroupData = { ...configGroupData };
- set(
- newConfigGroupData,
- "items",
- get(newConfigGroupData, "items", []).filter(
- (item) => get(item, "ConfigGroup.group_name") !== configGroupName
- )
- );
- setConfigGroupData(newConfigGroupData);
- };
-
const updateConfigGroup = (
configGroupName: string,
configGroupItem: ConfigGroupItemType
@@ -402,20 +396,21 @@ export default function ManageConfigGroups({
const unsetConfigGroupModal = () => {
setShowCreateNewConfigGroupModal(false);
isRenameConfigGroup.current = false;
+ isDuplicateConfigGroup.current = false;
config.current = {
name: "",
description: "",
};
};
- const getHostsForDefaultGroup = () => {
- const defaultGroup = getItemFromConfigGroups(configGroupData, "Default");
- if (!defaultGroup) return [];
- const hosts = get(defaultGroup, "[0].ConfigGroup.hosts", []).map(
- (host) => host.host_name
+ const getHostsAvailableForSelectedGroup = () => {
+ const selectedGroupHosts = new Set(
+ (getPropertyFromSelectedConfig("hosts") || []).map(
+ (host: { host_name?: string }) => host.host_name
+ )
);
- return get(hostData, "items", []).filter((host) =>
- hosts.includes(get(host, "Hosts.host_name"))
+ return get(hostData, "items", []).filter(
+ (host) => !selectedGroupHosts.has(get(host, "Hosts.host_name"))
);
};
@@ -447,40 +442,6 @@ export default function ManageConfigGroups({
return size;
};
- const removeHostsFromGroup = (
- groupName: string,
- hostsToBeRemoved: string[]
- ) => {
- // Use deep clone to avoid reference issues
- let newConfigGroupData = cloneDeep(configGroupData);
- get(newConfigGroupData, "items", []).forEach((configGroup) => {
- if (get(configGroup, "ConfigGroup.group_name") === groupName) {
- let newHosts = get(configGroup, "ConfigGroup.hosts", []).filter(
- (host) => !hostsToBeRemoved.includes(get(host, "host_name", ""))
- );
- set(configGroup, "ConfigGroup.hosts", newHosts);
- }
- });
- setConfigGroupData(newConfigGroupData);
- };
-
- const addHostsToGroup = (groupName: string, hostsToBeAdded: string[]) => {
- let newConfigGroupData = cloneDeep(configGroupData);
- get(newConfigGroupData, "items", []).forEach((configGroup) => {
- if (get(configGroup, "ConfigGroup.group_name") === groupName) {
- let additionalHosts = hostsToBeAdded.map((host: string) => {
- return {
- host_name: host,
- };
- });
- let existingHosts = cloneDeep(get(configGroup, "ConfigGroup.hosts", []));
- let newHosts = [...existingHosts, ...additionalHosts];
- set(configGroup, "ConfigGroup.hosts", newHosts);
- }
- });
- setConfigGroupData(newConfigGroupData);
- };
-
const doesConfigsMatch = (
configGroup1: ConfigGroupItemType,
configGroup2: ConfigGroupItemType,
@@ -511,7 +472,14 @@ export default function ManageConfigGroups({
return {
ConfigGroup: {
description: get(configGroup, "ConfigGroup.description", ""),
- desired_configs: get(configGroup, "ConfigGroup.desired_configs", []),
+ desired_configs: get(
+ configGroup,
+ "ConfigGroup.desired_configs",
+ []
+ ).map((config: DesiredConfigsItemType) => ({
+ type: get(config, "type"),
+ tag: get(config, "tag"),
+ })),
group_name: get(configGroup, "ConfigGroup.group_name", ""),
hosts: get(configGroup, "ConfigGroup.hosts", []).map((host) => {
return {
@@ -537,7 +505,10 @@ export default function ManageConfigGroups({
};
const handleSave = async () => {
- if (clusterName) {
+ setSaving(true);
+ setSaveError("");
+ try {
+ if (clusterName) {
const configGroupsToBeDeleted = get(
previousConfigGroupData.current,
"items",
@@ -575,39 +546,51 @@ export default function ManageConfigGroups({
)
);
- const addApiPromises = configGroupsToBeAdded.map((configGroup) =>
- ConfigGroupApi.addConfigGroup(clusterName, [
- getDataForApiFormat(configGroup),
- ])
+ const { toClear, toSet } = buildConfigGroupUpdatePlan(
+ get(previousConfigGroupData.current, "items", []),
+ configGroupsToBeUpdated
);
- const deleteApiPromises = configGroupsToBeDeleted.map((configGroup) =>
- ConfigGroupApi.removeConfigGroup(
- clusterName,
- get(configGroup, "ConfigGroup.id", "").toString()
+ // Ambari enforces one non-default group per service. Clear source hosts
+ // before assigning them to a target group or deleting their old group.
+ await Promise.all(
+ [...configGroupsToBeDeleted, ...toClear].map((configGroup) => {
+ const data = getDataForApiFormat(configGroup);
+ return ConfigGroupApi.updateConfigGroup(
+ clusterName,
+ get(configGroup, "ConfigGroup.id", "").toString(),
+ {
+ ...data,
+ ConfigGroup: { ...data.ConfigGroup, hosts: [] },
+ }
+ );
+ })
+ );
+ await Promise.all(
+ configGroupsToBeDeleted.map((configGroup) =>
+ ConfigGroupApi.removeConfigGroup(
+ clusterName,
+ get(configGroup, "ConfigGroup.id", "").toString()
+ )
)
);
-
- const updateApiPromises = configGroupsToBeUpdated.map((configGroup) =>
- ConfigGroupApi.updateConfigGroup(
- clusterName,
- get(configGroup, "ConfigGroup.id", "").toString(),
- getDataForApiFormat(configGroup)
+ await Promise.all(
+ toSet.map((configGroup) =>
+ ConfigGroupApi.updateConfigGroup(
+ clusterName,
+ get(configGroup, "ConfigGroup.id", "").toString(),
+ getDataForApiFormat(configGroup)
+ )
)
);
-
- if (
- addApiPromises.length ||
- deleteApiPromises.length ||
- updateApiPromises.length
- ) {
- await Promise.all([
- ...addApiPromises,
- ...deleteApiPromises,
- ...updateApiPromises,
- ]);
- }
- } else {
+ await Promise.all(
+ configGroupsToBeAdded.map((configGroup) =>
+ ConfigGroupApi.addConfigGroup(clusterName, [
+ getDataForApiFormat(configGroup),
+ ])
+ )
+ );
+ } else {
const prevState = get(
state,
"clusterCreationSteps.step7.data.configGroupData",
@@ -620,14 +603,23 @@ export default function ManageConfigGroups({
data: { ...prevState, configGroupData: configGroupData },
},
});
+ }
+
+ successCallback();
+ onClose();
+ } catch (error) {
+ setSaveError(
+ String(
+ get(
+ error,
+ "response.data.message",
+ get(error, "message", "Unable to save configuration groups.")
+ )
+ )
+ );
+ } finally {
+ setSaving(false);
}
-
- // Trigger config group refresh in all components that use config groups
- // This ensures that ChooseConfigGroup and other components refresh their data
- successCallback();
-
- // Close the modal after successful save
- onClose();
};
const isRemoveHostDisabled = () => {
@@ -635,7 +627,10 @@ export default function ManageConfigGroups({
};
const isAddHostDisabled = () => {
- return selectedGroup === "Default" || !getHostsForDefaultGroup().length;
+ return (
+ selectedGroup === "Default" ||
+ !getHostsAvailableForSelectedGroup().length
+ );
};
if (loading) {
@@ -661,6 +656,13 @@ export default function ManageConfigGroups({
} else {
set(formConfig, "ConfigGroup.hosts", []);
set(formConfig, "ConfigGroup.tag", serviceName);
+ set(
+ formConfig,
+ "ConfigGroup.desired_configs",
+ isDuplicateConfigGroup.current
+ ? cloneDeep(getPropertyFromSelectedConfig("desired_configs"))
+ : []
+ );
addConfigGroup(formConfig);
}
}}
@@ -678,13 +680,13 @@ export default function ManageConfigGroups({
modalTitle="Confirmation"
modalBody="Are you sure?"
successCallback={() => {
- addHostsToGroup(
- "Default",
- getPropertyFromSelectedConfig("hosts").map(
- (host: { [key: string]: string }) => host?.host_name
- )
- );
- removeConfigGroup(selectedGroup);
+ setConfigGroupData((current) => ({
+ ...current,
+ items: removeConfigGroupAndReturnHosts(
+ current.items,
+ selectedGroup
+ ),
+ }));
setSelectedGroup("Default");
setShowConfirmationModal(false);
}}
@@ -713,41 +715,17 @@ export default function ManageConfigGroups({
onClose={() => setShowSelectConfigHostsModal(false)}
successCallback={(hostsToBeAdded: any) => {
setShowSelectConfigHostsModal(false);
-
- let newConfigGroupData = cloneDeep(configGroupData);
-
- get(newConfigGroupData, "items", []).forEach((configGroup) => {
- //@ts-ignore
- const groupName = get(configGroup, "ConfigGroup.group_name");
- const currentHosts = get(configGroup, "ConfigGroup.hosts", []);
-
- // Remove hosts that are being moved to the new group
- const hostsToKeep = currentHosts.filter(
- (host) => !hostsToBeAdded.includes(get(host, "host_name", ""))
- );
-
- set(configGroup, "ConfigGroup.hosts", hostsToKeep);
- });
-
- // Then, add hosts to the selected group
- get(newConfigGroupData, "items", []).forEach((configGroup) => {
- if (get(configGroup, "ConfigGroup.group_name") === selectedGroup) {
- let additionalHosts = hostsToBeAdded.map((host: string) => {
- return {
- host_name: host,
- };
- });
- let existingHosts = cloneDeep(get(configGroup, "ConfigGroup.hosts", []));
- let newHosts = [...existingHosts, ...additionalHosts];
- set(configGroup, "ConfigGroup.hosts", newHosts);
- }
- });
-
- // Update state once with both changes
- setConfigGroupData(newConfigGroupData);
+ setConfigGroupData((current) => ({
+ ...current,
+ items: moveHostsToConfigGroup(
+ current.items,
+ selectedGroup,
+ hostsToBeAdded
+ ),
+ }));
}}
configGroupName={selectedGroup}
- hostsList={getHostsForDefaultGroup()}
+ hostsList={getHostsAvailableForSelectedGroup()}
/>
) : null}
<ReactModal
@@ -764,6 +742,7 @@ export default function ManageConfigGroups({
handleSave();
}}>
<ReactModal.Body>
+ {saveError ? <Alert variant="danger">{saveError}</Alert> : null}
<Alert variant="info" className="text-muted fs-12 mb-5">
You can apply different sets of {serviceName} configurations to
groups of hosts by managing {serviceName} Configuration Groups and
@@ -800,8 +779,7 @@ export default function ManageConfigGroups({
})}
</Card>
<div className="d-flex justify-content-end">
- {/* Create Config Group - Requires SERVICE.MODIFY_CONFIGS authorization */}
- {canModifyConfigs && (
+ {canManageConfigGroups && (
<DefaultButton
className="me-2"
onClick={() => setShowCreateNewConfigGroupModal(true)}
@@ -809,8 +787,7 @@ export default function ManageConfigGroups({
<FontAwesomeIcon icon={faPlus} />
</DefaultButton>
)}
- {/* Delete Config Group - Requires SERVICE.MODIFY_CONFIGS authorization */}
- {canModifyConfigs && (
+ {canManageConfigGroups && (
<DefaultButton
className={
selectedGroup === "Default"
@@ -823,8 +800,7 @@ export default function ManageConfigGroups({
<FontAwesomeIcon icon={faMinus} />
</DefaultButton>
)}
- {/* Edit Config Group Dropdown - Requires SERVICE.MODIFY_CONFIGS authorization */}
- {canModifyConfigs && (
+ {canManageConfigGroups && (
<Dropdown>
<Dropdown.Toggle
variant="transparent"
@@ -855,10 +831,12 @@ export default function ManageConfigGroups({
<Dropdown.Item
onClick={() => {
isRenameConfigGroup.current = false;
+ isDuplicateConfigGroup.current = true;
config.current = {
name: selectedGroup + " Copy",
- description:
- getPropertyFromSelectedConfig("description"),
+ description: `${getPropertyFromSelectedConfig(
+ "description"
+ )} (Copy)`,
};
setShowCreateNewConfigGroupModal(true);
}}
@@ -893,8 +871,7 @@ export default function ManageConfigGroups({
)}
</Card>
<div className="d-flex justify-content-end">
- {/* Add Hosts to Config Group - Requires SERVICE.MODIFY_CONFIGS authorization */}
- {canModifyConfigs && (
+ {canManageConfigGroups && (
<DefaultButton
className={
isAddHostDisabled() ? "disabled-btn me-2" : "me-2"
@@ -905,14 +882,19 @@ export default function ManageConfigGroups({
<FontAwesomeIcon icon={faPlus} />
</DefaultButton>
)}
- {/* Remove Hosts from Config Group - Requires SERVICE.MODIFY_CONFIGS authorization */}
- {canModifyConfigs && (
+ {canManageConfigGroups && (
<DefaultButton
className={isRemoveHostDisabled() ? "disabled-btn" : ""}
disabled={isRemoveHostDisabled()}
onClick={() => {
- removeHostsFromGroup(selectedGroup, selectedHosts);
- addHostsToGroup("Default", selectedHosts);
+ setConfigGroupData((current) => ({
+ ...current,
+ items: moveHostsToConfigGroup(
+ current.items,
+ "Default",
+ selectedHosts
+ ),
+ }));
setSelectedHosts([]);
}}
>
@@ -946,23 +928,22 @@ export default function ManageConfigGroups({
</ReactModal.Body>
<ReactModal.Footer>
<DefaultButton onClick={onClose}>CANCEL</DefaultButton>
- {/* Save Config Groups - Requires SERVICE.MODIFY_CONFIGS authorization */}
- {canModifyConfigs && (
+ {canManageConfigGroups && (
<Button
type="submit"
className={classNames("custom-btn text-white", {
"disabled-btn": !enableSave,
})}
- disabled={!enableSave}
+ disabled={!enableSave || saving}
>
- SAVE
+ {saving ? "SAVING" : "SAVE"}
</Button>
)}
{/* Show unauthorized message if user lacks permissions */}
- {!canModifyConfigs && (
+ {!canManageConfigGroups && (
<div className="text-muted small">
You do not have permission to modify configuration groups.
- Required permission: SERVICE.MODIFY_CONFIGS
+ Required permission: SERVICE.MANAGE_CONFIG_GROUPS
</div>
)}
</ReactModal.Footer>
diff --git a/ambari-web/latest/src/screens/ConfigGroups/SelectConfigGroupHosts.tsx b/ambari-web/latest/src/screens/ConfigGroups/SelectConfigGroupHosts.tsx
index bded766193..c1b8203543 100644
--- a/ambari-web/latest/src/screens/ConfigGroups/SelectConfigGroupHosts.tsx
+++ b/ambari-web/latest/src/screens/ConfigGroups/SelectConfigGroupHosts.tsx
@@ -63,7 +63,7 @@ export default function SelectConfigGroupHosts({
const [filterString, setFilterString] = useState<string>("");
useEffect(() => {
- const currentHosts = hostsList.map((host) => {
+ const currentHosts = cloneDeep(hostsList).map((host) => {
set(host, "isChecked", false);
set(host, "isShown", true);
let totalDiskCapacity =
@@ -83,7 +83,7 @@ export default function SelectConfigGroupHosts({
return host;
});
setHosts(currentHosts);
- }, []);
+ }, [hostsList]);
useEffect(() => {
if (hosts.length) {
@@ -245,13 +245,14 @@ export default function SelectConfigGroupHosts({
<h2>Select Configuration Group Hosts</h2>
</ReactModal.Header>
<Form
- onSubmit={() =>
+ onSubmit={(event) => {
+ event.preventDefault();
successCallback(
getHostsWithProperty("isChecked").map((host) =>
get(host, "Hosts.host_name", "")
)
)
- }
+ }}
>
<ReactModal.Body>
<Alert variant="info" className="text-muted fs-12 mb-4">
diff --git a/ambari-web/latest/src/screens/ConfigVersions/VersionsList.tsx b/ambari-web/latest/src/screens/ConfigVersions/VersionsList.tsx
index 482587bf42..c7886c6d10 100644
--- a/ambari-web/latest/src/screens/ConfigVersions/VersionsList.tsx
+++ b/ambari-web/latest/src/screens/ConfigVersions/VersionsList.tsx
@@ -39,6 +39,7 @@ import { ServiceConfigApi } from "../../api/serviceConfigApi";
import { AppContext } from "../../store/context";
import { toast } from "react-hot-toast";
import Config from "../CommonConfigs/Config";
+import { useAuth } from "../../hooks/useAuth";
interface VersionsListProps {
serviceName: string;
@@ -75,20 +76,13 @@ export const VersionsList = ({
const [serviceConfigVersionNote, setServiceConfigVersionNote] = useState("");
const [makeCurrentNote, setMakeCurrentNote] = useState("");
const [isDropdownOpen, setIsDropdownOpen] = useState(false);
- const selectedServices = [
- "RANGER_KMS",
- "AMBARI_METRICS",
- "RANGER",
- "YARN",
- "ZOOKEEPER",
- "HIVE",
- "TEZ",
- "HBASE",
- "MAPREDUCE2",
- "SPARK3",
- ];
-
- const {clusterName} = useContext(AppContext);
+ const { clusterName, services } = useContext(AppContext);
+ const { hasAuthorization } = useAuth();
+ const canCompareConfigs = hasAuthorization("SERVICE.COMPARE_CONFIGS");
+ const canModifyConfigs = hasAuthorization("SERVICE.MODIFY_CONFIGS");
+ const selectedServices = services.map(
+ (service) => service.ServiceInfo.service_name
+ );
useEffect(()=>{
setCurrentVersionParent?.(currentVersion)
@@ -233,7 +227,7 @@ export const VersionsList = ({
const setVersion = async () => {
try {
- await ServiceConfigApi.setIsCurrent(clusterName, selectedServices);
+ await ServiceConfigApi.getCurrentServiceConfigs(clusterName, selectedServices);
} catch (error) {
console.error("Failed to set current version", error);
throw error;
@@ -277,7 +271,7 @@ export const VersionsList = ({
<strong style={{ fontWeight: "bold" }}>{currentVersion}</strong>
</Dropdown.Toggle>
<span id="make-current-btn" className="ms-1">
- {previousVersion !== currentVersion && !isComparing ? (
+ {previousVersion !== currentVersion && !isComparing && canModifyConfigs ? (
<Button
className="rounded-1 border-1 hover-effect-make-current-btn"
onClick={() => {
@@ -388,7 +382,7 @@ export const VersionsList = ({
</div>
</Dropdown.Item>
</Card>
- {item.version !== currentVersion && !isComparing && (
+ {item.version !== currentVersion && !isComparing && canCompareConfigs && (
<OverlayTrigger placement="top" overlay={renderTooltip}>
<span className="pointer-transition">
{/*<FaExchangeAlt className="ms-2" onClick={() => handleCompareVersions(item.version)} />*/}
diff --git a/ambari-web/latest/src/screens/ServiceConfigs/index.tsx b/ambari-web/latest/src/screens/ServiceConfigs/index.tsx
index b11aed4e68..cd9a1c0314 100644
--- a/ambari-web/latest/src/screens/ServiceConfigs/index.tsx
+++ b/ambari-web/latest/src/screens/ServiceConfigs/index.tsx
@@ -1205,14 +1205,21 @@ export default function ServiceConfigs({
);
}
- function saveConfigs() {
- saveStepConfigs();
+ async function saveConfigs() {
+ const saved = await saveStepConfigs();
+ if (!saved) {
+ return false;
+ }
+
setShowSaveConfigModal(false);
setShowValidationErrorsModal(false);
+ setShowUnsaveChangesModal(false);
setServiceConfigVersionNote("");
- setTimeout(() => {
- getPropertiesValues();
- }, 1000);
+ await getPropertiesValues();
+ if (blocker.state === "blocked") {
+ blocker.proceed();
+ }
+ return true;
}
if (!configsLoaded || loading) {
@@ -1239,9 +1246,6 @@ export default function ServiceConfigs({
modalBody={getValidationsModalBody()}
successCallback={() => {
saveConfigs();
- if (blocker.state === 'blocked') {
- blocker.proceed();
- }
}}
options={{
okButtonText: "PROCEED ANYWAYS",
diff --git a/ambari-web/latest/src/screens/Services/Actions.tsx b/ambari-web/latest/src/screens/Services/Actions.tsx
index d1ed99e2d8..551ab44b24 100644
--- a/ambari-web/latest/src/screens/Services/Actions.tsx
+++ b/ambari-web/latest/src/screens/Services/Actions.tsx
@@ -61,7 +61,6 @@ import BackgroundOperations from "../BackgroundOperations";
import modalManager from "../../store/ModalManager";
import ReassignComponent from "./reassign";
import {
- displayNameServiceMapping,
// selectClientComponentsForService,
// selectMasterComponentsForService,
// selectSlaveComponentsForService,
@@ -104,6 +103,7 @@ import {
translate,
translateWithVariables,
} from "../../Utils/Utility";
+import { canManageServices } from "../../Utils/servicePermissions";
interface ActionsProps {
serviceName: string;
@@ -121,7 +121,9 @@ export const Actions = ({ serviceName, className }: ActionsProps) => {
clusterName,
upgradeIsRunning,
upgradeSuspended,
- isClusterInstalled
+ isClusterInstalled,
+ supports,
+ wizardIsNotFinished,
} = useContext(AppContext);
const { allServiceModels } = useContext(ServiceContext);
@@ -130,11 +132,8 @@ export const Actions = ({ serviceName, className }: ActionsProps) => {
// Check specific authorizations like in Ember.js ui/app/views/main/service/item.js
const canStartStop = hasAuthorization("SERVICE.START_STOP");
- const canRunCustomCommands =
- hasAuthorization("SERVICE.RUN_CUSTOM_COMMAND") ||
- hasAuthorization("SERVICE.RUN_SERVICE_CHECK") ||
- hasAuthorization("SERVICE.TOGGLE_MAINTENANCE") ||
- hasAuthorization("SERVICE.ENABLE_HA");
+ const canRunCustomCommands = hasAuthorization("SERVICE.RUN_CUSTOM_COMMAND");
+ const canRunServiceCheck = hasAuthorization("SERVICE.RUN_SERVICE_CHECK");
const canAddDeleteServices = hasAuthorization("SERVICE.ADD_DELETE_SERVICES");
const canAddDeleteComponents = hasAuthorization("HOST.ADD_DELETE_COMPONENTS");
const canEnableHA = hasAuthorization("SERVICE.ENABLE_HA");
@@ -149,7 +148,7 @@ export const Actions = ({ serviceName, className }: ActionsProps) => {
canAddDeleteComponents ||
canEnableHA ||
canMoveComponents ||
- hasAuthorization("SERVICE.RUN_SERVICE_CHECK") ||
+ canRunServiceCheck ||
hasAuthorization("SERVICE.TOGGLE_MAINTENANCE");
// Use computed upgrade properties instead of basic state checks
@@ -766,25 +765,42 @@ export const Actions = ({ serviceName, className }: ActionsProps) => {
};
const toggleMaintenanceMode = async () => {
- //@ts-ignore
- await ActionsApi.turnOnOffMaintenance(
- clusterName,
- // @ts-ignore
- serviceName,
- {
+ const targetState = desiredMaintenceState();
+ try {
+ await ActionsApi.turnOnOffMaintenance(clusterName, serviceName, {
requestInfo: `Turn ${startCase(
- lowerCase(desiredMaintenceState())
+ lowerCase(targetState)
)} Maintenance Mode for ${serviceName}`,
- passive_state: desiredMaintenceState(),
- }
- );
- setModalInfo({
- title: `Information`,
- body: `Maintenance Mode has been turned ${lowerCase(
- desiredMaintenceState()
- )}. It may take a few minutes for the alerts to be suppressed.`,
- });
- setShowConfirmationModal(true);
+ passive_state: targetState,
+ });
+ setServiceState((currentState: Record<string, unknown>) => ({
+ ...currentState,
+ maintenance_state: targetState,
+ }));
+ setModalInfo({
+ title: `Information`,
+ body: `Maintenance Mode has been turned ${lowerCase(
+ targetState
+ )}. It may take a few minutes for the alerts to be suppressed.`,
+ });
+ setShowConfirmationModal(true);
+ } catch (error) {
+ const message = get(
+ error,
+ "response.data.message",
+ get(error, "message", "Maintenance Mode could not be updated.")
+ );
+ modalManager.show({
+ modalTitle: "Maintenance Mode Failed",
+ modalBody: message,
+ successCallback: () => {
+ modalManager.hide();
+ void toggleMaintenanceMode();
+ },
+ onClose: () => modalManager.hide(),
+ options: { okButtonText: "RETRY" },
+ });
+ }
};
const desiredMaintenceState = (): string => {
return get(serviceState, "maintenance_state", "") === "OFF" ? "ON" : "OFF";
@@ -1095,15 +1111,6 @@ export const Actions = ({ serviceName, className }: ActionsProps) => {
}
};
- const getClientName = () => {
- const serviceObject = get(
- serviceModels,
- get(serviceNameModelMapping, get(displayNameServiceMapping, serviceName)),
- {}
- );
- return get(serviceObject, "clientComponents.[0].componentName", "");
- };
-
const handleThresholdChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value;
//is a number
@@ -1932,7 +1939,7 @@ export const Actions = ({ serviceName, className }: ActionsProps) => {
);
// Return the mapped components
- return filteredComponentActions.map((componentAction) => (
+ return canStartStop ? filteredComponentActions.map((componentAction) => (
<DropdownItem
key={componentAction.component}
onClick={() => restartComponent(componentAction.component)}
@@ -1949,7 +1956,7 @@ export const Actions = ({ serviceName, className }: ActionsProps) => {
: null
}
</DropdownItem>
- ));
+ )) : null;
})()}
{/* High Availability Features - Requires SERVICE.ENABLE_HA authorization */}
{canEnableHA && serviceName === "HDFS" && !isHAEnabled() && (
@@ -1959,8 +1966,7 @@ export const Actions = ({ serviceName, className }: ActionsProps) => {
{canEnableHA && serviceName === "HDFS" && (
<EnableNamenodeFederation />
)}
- {/* Manage JournalNodes - No specific authorization required, only HA state and host count checks */}
- {serviceName === "HDFS" && canManageJournalNodes() && (
+ {canEnableHA && serviceName === "HDFS" && canManageJournalNodes() && (
<ManageJournalNodes />
)}
{canEnableHA && serviceName === "YARN" && !isRMHAEnabled() && (
@@ -1990,9 +1996,8 @@ export const Actions = ({ serviceName, className }: ActionsProps) => {
onClick={() => {
downloadClientConfigsCall({
clusterName: clusterName,
- componentName: getClientName(),
serviceName: serviceName,
- resourceType: ResourceTypeEnum.SERVICE_COMPONENT,
+ resourceType: ResourceTypeEnum.SERVICE,
});
}}
>
@@ -2009,7 +2014,7 @@ export const Actions = ({ serviceName, className }: ActionsProps) => {
</Dropdown.Item>
)}
- {serviceName === "HDFS" ? (
+ {canRunCustomCommands && serviceName === "HDFS" ? (
<DropdownItem
// key={componentAction.component}
onClick={() => rebalanceComponent()}
@@ -2206,7 +2211,7 @@ export const Actions = ({ serviceName, className }: ActionsProps) => {
Add Zookeeper Server
</Dropdown.Item>
)}
- {serviceName === "HDFS" ? (
+ {canRunCustomCommands && serviceName === "HDFS" ? (
<DropdownItem
onClick={async () => {
//show popup modal
@@ -2236,7 +2241,7 @@ export const Actions = ({ serviceName, className }: ActionsProps) => {
{ServiceActionEnums.refreshNodes}
</DropdownItem>
) : null}
- {serviceName === "YARN" ? (
+ {canRunCustomCommands && serviceName === "YARN" ? (
<DropdownItem
onClick={async () => {
//show popup modal
@@ -2273,7 +2278,11 @@ export const Actions = ({ serviceName, className }: ActionsProps) => {
)}
{/* Service Deletion - Requires SERVICE.ADD_DELETE_SERVICES authorization */}
- {canAddDeleteServices && (
+ {canManageServices({
+ authorized: canAddDeleteServices,
+ featureEnabled: supports.enableAddDeleteServices,
+ wizardIsNotFinished,
+ }) && (
<DropdownItem
onClick={() => {
const serviceModel =
@@ -2357,11 +2366,8 @@ export const Actions = ({ serviceName, className }: ActionsProps) => {
</DropdownItem>
)}
- {/* Service Check - Requires SERVICE.RUN_CUSTOM_COMMAND, SERVICE.RUN_SERVICE_CHECK, SERVICE.TOGGLE_MAINTENANCE, or SERVICE.ENABLE_HA authorization (matches Ember.js logic) */}
- {(hasAuthorization("SERVICE.RUN_CUSTOM_COMMAND") ||
- hasAuthorization("SERVICE.RUN_SERVICE_CHECK") ||
- hasAuthorization("SERVICE.TOGGLE_MAINTENANCE") ||
- hasAuthorization("SERVICE.ENABLE_HA")) && (
+ {/* Service Check uses its semantic service-check authorization. */}
+ {canRunServiceCheck && (
<DropdownItem
// key={serviceName}
onClick={() => runServiceCheck()}
diff --git a/ambari-web/latest/src/screens/Services/AddServiceWizard/wizardDataStore/context.tsx b/ambari-web/latest/src/screens/Services/AddServiceWizard/wizardDataStore/context.tsx
index cca6ec03f1..44c579cbcc 100644
--- a/ambari-web/latest/src/screens/Services/AddServiceWizard/wizardDataStore/context.tsx
+++ b/ambari-web/latest/src/screens/Services/AddServiceWizard/wizardDataStore/context.tsx
@@ -37,6 +37,10 @@ import { getAllComponents } from "../../../Hosts/utils";
import { ServiceApi } from "../../../../api/serviceApi";
import { ClusterProgressStatus } from "../../../../constants";
import modalManager from "../../../../store/ModalManager";
+import {
+ CANCEL_ADD_SERVICE_WIZARD_EVENT,
+ clearAddServiceWizardState,
+} from "../../../../Utils/addServicePersistence";
interface AddServiceContextProps {
state: State;
@@ -73,6 +77,7 @@ export const AddServiceProvider: React.FC<{
const isCancelled = useRef(false);
const requestSequence = useRef(0);
const debounceTimer = useRef<NodeJS.Timeout | null>(null);
+ const cancelWizardRef = useRef<(() => Promise<void>) | null>(null);
// Custom debounced persist function with cancellation capability
const debouncedPersist = () => {
@@ -385,15 +390,7 @@ export const AddServiceProvider: React.FC<{
try {
// Clear the persisted state with the latest sequence number
- await ClusterApi.postPersistData(
- JSON.stringify({
- ADD_SERVICE: JSON.stringify({
- ...initialState,
- requestSequence: cancelSequence,
- }),
- CLUSTER_STATE: JSON.stringify({}),
- })
- );
+ await clearAddServiceWizardState(initialState, cancelSequence);
} catch (error: any) {
console.error('Error clearing persisted data:', error);
} finally {
@@ -403,6 +400,23 @@ export const AddServiceProvider: React.FC<{
}
}
+ cancelWizardRef.current = flushOnCancel;
+
+ useEffect(() => {
+ const cancelWizard = () => {
+ void cancelWizardRef.current?.();
+ };
+ window.addEventListener(CANCEL_ADD_SERVICE_WIZARD_EVENT, cancelWizard);
+ return () => {
+ window.removeEventListener(CANCEL_ADD_SERVICE_WIZARD_EVENT, cancelWizard);
+ if (debounceTimer.current) {
+ clearTimeout(debounceTimer.current);
+ debounceTimer.current = null;
+ }
+ isCancelled.current = true;
+ };
+ }, []);
+
async function flushOnStepChange(nextStep: number) {
if (nextStep >= 1) {
let nextStepDetails = stepWizardUtilities.wizardSteps?.[nextStep];
@@ -437,19 +451,15 @@ export const AddServiceProvider: React.FC<{
);
switch (operation) {
case "cancel":
- flushOnCancel();
- break;
+ return flushOnCancel();
case "back":
- flushOnStepChange(Number(activeStep) - 1);
- break;
+ return flushOnStepChange(Number(activeStep) - 1);
case "next":
- flushOnStepChange(Number(activeStep) + 1);
- break;
+ return flushOnStepChange(Number(activeStep) + 1);
case "jump":
- flushOnStepChange(jumpStep);
- break;
+ return flushOnStepChange(jumpStep);
default:
- flushCurrentData();
+ return flushCurrentData();
}
}
diff --git a/ambari-web/latest/src/screens/Services/AddWizardUrlMapping.tsx b/ambari-web/latest/src/screens/Services/AddWizardUrlMapping.tsx
index c39d91129e..73cfe080ee 100644
--- a/ambari-web/latest/src/screens/Services/AddWizardUrlMapping.tsx
+++ b/ambari-web/latest/src/screens/Services/AddWizardUrlMapping.tsx
@@ -30,10 +30,10 @@ import {
AddHostProvider,
} from "../Hosts/AddHostWizard/wizardDataStore/context";
import addHostWizardSteps from "../Hosts/AddHostWizard/addHostWizardSteps";
-import { useContext } from "react";
+import { ComponentProps, useContext } from "react";
+import { CANCEL_ADD_SERVICE_WIZARD_EVENT } from "../../Utils/addServicePersistence";
function AddWizardUrlMapping() {
- const {flushStateToDb} = useContext(AddHostContext)
const location = useLocation();
function mapUrlToComponent() {
if (location.pathname.includes("service/add")) {
@@ -56,8 +56,9 @@ function AddWizardUrlMapping() {
modalManager.hide();
}}
successCallback={() => {
- modalManager.hide();
- window.location.href = "/#/main/dashboard/metrics";
+ window.dispatchEvent(
+ new Event(CANCEL_ADD_SERVICE_WIZARD_EVENT)
+ );
}}
/>
);
@@ -79,50 +80,61 @@ function AddWizardUrlMapping() {
></Modal>
);
} else if (location.pathname.includes("host/add")) {
- return (
- <Modal
- isOpen={true}
- onClose={() => {
- modalManager.show(
- <Modal
- options={{}}
- modalTitle="Confirmation"
- isOpen={true}
- modalBody={
- <div>
- Are you sure you want to cancel the host addition? All your
- progress will be lost.
- </div>
- }
- onClose={() => {
- flushStateToDb("cancel");
- modalManager.hide();
- }}
- successCallback={() => {
- modalManager.hide();
- window.location.href = "/#/main/hosts";
- }}
- />
- );
- }}
- modalTitle="Add Hosts"
- options={{
- modalSize: "modal-wizard",
- shouldShowFooter: false,
- }}
- successCallback={() => {}}
- modalBody={
- <ClusterCreationWizard
- Context={AddHostContext}
- Provider={AddHostProvider}
- wizardSteps={addHostWizardSteps as any}
- initialActiveStep={1}
- />
- }
- ></Modal>
- );
+ return <AddHostWizardModal />;
}
}
return mapUrlToComponent();
}
+
+function AddHostWizardModal() {
+ const { flushStateToDb } = useContext(AddHostContext);
+
+ return (
+ <Modal
+ isOpen={true}
+ onClose={() => {
+ modalManager.show(
+ <Modal
+ options={{}}
+ modalTitle="Confirmation"
+ isOpen={true}
+ modalBody={
+ <div>
+ Are you sure you want to cancel the host addition? All your
+ progress will be lost.
+ </div>
+ }
+ onClose={() => {
+ flushStateToDb("cancel");
+ modalManager.hide();
+ }}
+ successCallback={() => {
+ modalManager.hide();
+ window.location.href = "/#/main/hosts";
+ }}
+ />
+ );
+ }}
+ modalTitle="Add Hosts"
+ options={{
+ modalSize: "modal-wizard",
+ shouldShowFooter: false,
+ }}
+ successCallback={() => {}}
+ modalBody={
+ <ClusterCreationWizard
+ Context={AddHostContext}
+ Provider={AddHostProvider}
+ wizardSteps={
+ addHostWizardSteps as unknown as ComponentProps<
+ typeof ClusterCreationWizard
+ >["wizardSteps"]
+ }
+ initialActiveStep={1}
+ />
+ }
+ />
+ );
+}
+
export default AddWizardUrlMapping;
diff --git a/ambari-web/latest/src/screens/Services/FlumeSummary.test.tsx b/ambari-web/latest/src/screens/Services/FlumeSummary.test.tsx
new file mode 100644
index 0000000000..8a30e5a44a
--- /dev/null
+++ b/ambari-web/latest/src/screens/Services/FlumeSummary.test.tsx
@@ -0,0 +1,194 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import {
+ act,
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import { ComponentProps, isValidElement } from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { AppContext } from "../../store/context";
+import { ServiceContext } from "../../store/ServiceContext";
+
+const mocks = vi.hoisted(() => ({
+ fetchAllServiceComponents: vi.fn(),
+ hasAuthorization: vi.fn(),
+ hideModal: vi.fn(),
+ showModal: vi.fn(),
+ updateFlumeAgent: vi.fn(),
+}));
+
+vi.mock("../../api/serviceApi", () => ({
+ ServiceApi: { updateFlumeAgent: mocks.updateFlumeAgent },
+}));
+vi.mock("../../api/cachedServiceApi", () => ({
+ cachedServiceApi: {
+ fetchAllServiceComponents: mocks.fetchAllServiceComponents,
+ },
+}));
+vi.mock("../../hooks/useAuth", () => ({
+ useAuth: () => ({ hasAuthorization: mocks.hasAuthorization }),
+}));
+vi.mock("../../store/ModalManager", () => ({
+ default: { hide: mocks.hideModal, show: mocks.showModal },
+}));
+vi.mock("../BackgroundOperations", () => ({
+ default: ({ requestId }: { requestId: number }) => (
+ <div>Background request {requestId}</div>
+ ),
+}));
+
+import FlumeSummary from "./FlumeSummary";
+
+const componentData = [
+ {
+ ServiceComponentInfo: {
+ service_name: "FLUME",
+ component_name: "FLUME_HANDLER",
+ },
+ host_components: [
+ {
+ HostRoles: { host_name: "host1" },
+ processes: [
+ {
+ HostComponentProcess: {
+ name: "stopped-agent",
+ status: "NOT_RUNNING",
+ },
+ },
+ {
+ HostComponentProcess: {
+ name: "running-agent",
+ status: "RUNNING",
+ },
+ },
+ ],
+ },
+ ],
+ },
+];
+
+const renderSummary = () => render(
+ <AppContext.Provider
+ value={
+ {
+ backgroundOperations: [],
+ clusterName: "c1",
+ wizardIsNotFinished: false,
+ } as unknown as ComponentProps<typeof AppContext.Provider>["value"]
+ }
+ >
+ <ServiceContext.Provider
+ value={
+ {
+ masterSlaveClientsData: componentData,
+ } as unknown as ComponentProps<typeof ServiceContext.Provider>["value"]
+ }
+ >
+ <FlumeSummary />
+ </ServiceContext.Provider>
+ </AppContext.Provider>
+);
+
+const confirmAction = (agentName: string, actionName: string) => {
+ fireEvent.click(
+ screen.getByRole("button", {
+ name: `Actions for Flume agent ${agentName} on host1`,
+ })
+ );
+ fireEvent.click(screen.getByText(actionName));
+ const confirmation = mocks.showModal.mock.calls.at(-1)?.[0];
+ expect(confirmation).toMatchObject({
+ modalTitle: "Confirmation",
+ options: { okButtonText: actionName.split(" ")[0].toUpperCase() },
+ });
+ return confirmation;
+};
+
+describe("Flume summary", () => {
+ afterEach(cleanup);
+
+ beforeEach(() => {
+ mocks.fetchAllServiceComponents.mockReset();
+ mocks.fetchAllServiceComponents.mockResolvedValue({});
+ mocks.hasAuthorization.mockReset();
+ mocks.hasAuthorization.mockReturnValue(true);
+ mocks.hideModal.mockReset();
+ mocks.showModal.mockReset();
+ mocks.updateFlumeAgent.mockReset();
+ mocks.updateFlumeAgent.mockResolvedValue({
+ data: { Requests: { id: 42 } },
+ });
+ });
+
+ it("submits a state-valid action and opens its background request", async () => {
+ renderSummary();
+ const confirmation = confirmAction("stopped-agent", "Start Agent");
+
+ await act(async () => confirmation.successCallback());
+
+ expect(mocks.updateFlumeAgent).toHaveBeenCalledWith(
+ "c1",
+ "host1",
+ "stopped-agent",
+ "STARTED",
+ "Start Flume Agent stopped-agent"
+ );
+ await waitFor(() => expect(mocks.showModal).toHaveBeenCalledTimes(2));
+ const backgroundModal = mocks.showModal.mock.calls.at(-1)?.[0];
+ expect(isValidElement(backgroundModal)).toBe(true);
+ expect(backgroundModal.props.requestId).toBe(42);
+ });
+
+ it("recovers from submission failure and exposes Retry", async () => {
+ mocks.updateFlumeAgent.mockRejectedValueOnce(new Error("submit failed"));
+ renderSummary();
+ const confirmation = confirmAction("running-agent", "Stop Agent");
+
+ await act(async () => confirmation.successCallback());
+
+ await waitFor(() => {
+ expect(mocks.showModal.mock.calls.at(-1)?.[0]).toMatchObject({
+ modalTitle: "Stop Flume Agent Failed",
+ modalBody: "submit failed",
+ options: { okButtonText: "RETRY" },
+ });
+ });
+ expect(
+ screen.getByRole("button", {
+ name: "Actions for Flume agent running-agent on host1",
+ }).hasAttribute("disabled")
+ ).toBe(false);
+
+ const failure = mocks.showModal.mock.calls.at(-1)?.[0];
+ await act(async () => failure.successCallback());
+ expect(mocks.updateFlumeAgent).toHaveBeenCalledTimes(2);
+ });
+
+ it("renders status without mutation controls when authorization is absent", () => {
+ mocks.hasAuthorization.mockReturnValue(false);
+ renderSummary();
+
+ expect(screen.getByText("Running")).toBeTruthy();
+ expect(screen.queryByRole("button")).toBeNull();
+ });
+});
diff --git a/ambari-web/latest/src/screens/Services/FlumeSummary.tsx b/ambari-web/latest/src/screens/Services/FlumeSummary.tsx
new file mode 100644
index 0000000000..e3d0aaf48f
--- /dev/null
+++ b/ambari-web/latest/src/screens/Services/FlumeSummary.tsx
@@ -0,0 +1,262 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+import {
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import { Dropdown, Spinner, Table } from "react-bootstrap";
+import { get } from "lodash";
+import {
+ canStartFlumeAgent,
+ canStopFlumeAgent,
+ extractFlumeAgents,
+ FlumeAgent,
+} from "../../Utils/flumeAgents";
+import { isOperationTerminal } from "../../Utils/backgroundOperations";
+import { ServiceApi } from "../../api/serviceApi";
+import { cachedServiceApi } from "../../api/cachedServiceApi";
+import BackgroundOperations from "../BackgroundOperations";
+import modalManager from "../../store/ModalManager";
+import { AppContext } from "../../store/context";
+import { ServiceContext } from "../../store/ServiceContext";
+import { useAuth } from "../../hooks/useAuth";
+
+type FlumeAction = "start" | "stop";
+
+type PendingAgent = {
+ action: FlumeAction;
+ agent: FlumeAgent;
+ requestId?: number;
+ targetStatus: FlumeAgent["status"];
+ refreshing?: boolean;
+};
+
+const displayStatus = (status: FlumeAgent["status"]) => ({
+ RUNNING: "Running",
+ NOT_RUNNING: "Stopped",
+ UNKNOWN: "Unknown",
+})[status];
+
+function FlumeSummary() {
+ const {
+ backgroundOperations,
+ clusterName,
+ wizardIsNotFinished,
+ } = useContext(AppContext);
+ const { masterSlaveClientsData } = useContext(ServiceContext);
+ const { hasAuthorization } = useAuth();
+ const [pendingAgents, setPendingAgents] = useState<Record<string, PendingAgent>>({});
+ const submitCommandRef = useRef<
+ (_agent: FlumeAgent, _action: FlumeAction) => Promise<void>
+ >(async () => undefined);
+ const agents = useMemo(
+ () => extractFlumeAgents(masterSlaveClientsData),
+ [masterSlaveClientsData]
+ );
+ const canStartStop = hasAuthorization("SERVICE.START_STOP") && !wizardIsNotFinished;
+
+ const removePendingAgent = useCallback((agentId: string) => {
+ setPendingAgents((current) => {
+ const next = { ...current };
+ delete next[agentId];
+ return next;
+ });
+ }, []);
+
+ const showFailure = useCallback((pending: PendingAgent, error: unknown) => {
+ const label = pending.action === "start" ? "Start" : "Stop";
+ const message = get(
+ error,
+ "response.data.message",
+ get(error, "message", `${label} Flume agent could not be submitted.`)
+ );
+ modalManager.show({
+ modalTitle: `${label} Flume Agent Failed`,
+ modalBody: message,
+ successCallback: () => {
+ modalManager.hide();
+ void submitCommandRef.current(pending.agent, pending.action);
+ },
+ onClose: () => modalManager.hide(),
+ options: { okButtonText: "RETRY" },
+ });
+ }, []);
+
+ const submitCommand = useCallback(async (
+ agent: FlumeAgent,
+ action: FlumeAction
+ ) => {
+ const targetState = action === "start" ? "STARTED" : "INSTALLED";
+ const targetStatus = action === "start" ? "RUNNING" : "NOT_RUNNING";
+ const label = action === "start" ? "Start" : "Stop";
+ const pending = { action, agent, targetStatus } as PendingAgent;
+ setPendingAgents((current) => ({ ...current, [agent.id]: pending }));
+
+ try {
+ const response = await ServiceApi.updateFlumeAgent(
+ clusterName,
+ agent.hostName,
+ agent.name,
+ targetState,
+ `${label} Flume Agent ${agent.name}`
+ );
+ const requestId = Number(get(response, "data.Requests.id"));
+ if (Number.isFinite(requestId)) {
+ setPendingAgents((current) => ({
+ ...current,
+ [agent.id]: { ...pending, requestId },
+ }));
+ modalManager.show(
+ <BackgroundOperations
+ isOpen
+ onClose={() => modalManager.hide()}
+ requestId={requestId}
+ />
+ );
+ } else {
+ await cachedServiceApi.fetchAllServiceComponents(clusterName, true);
+ removePendingAgent(agent.id);
+ }
+ } catch (error) {
+ removePendingAgent(agent.id);
+ showFailure(pending, error);
+ }
+ }, [clusterName, removePendingAgent, showFailure]);
+ submitCommandRef.current = submitCommand;
+
+ const confirmCommand = (agent: FlumeAgent, action: FlumeAction) => {
+ const label = action === "start" ? "Start" : "Stop";
+ modalManager.show({
+ modalTitle: "Confirmation",
+ modalBody: `${label} Flume agent ${agent.name} on ${agent.hostName}?`,
+ successCallback: () => {
+ modalManager.hide();
+ void submitCommand(agent, action);
+ },
+ onClose: () => modalManager.hide(),
+ options: { okButtonText: label.toUpperCase() },
+ });
+ };
+
+ useEffect(() => {
+ agents.forEach((agent) => {
+ const pending = pendingAgents[agent.id];
+ if (pending && agent.status === pending.targetStatus) {
+ removePendingAgent(agent.id);
+ }
+ });
+ }, [agents, pendingAgents, removePendingAgent]);
+
+ useEffect(() => {
+ Object.values(pendingAgents).forEach((pending) => {
+ if (!pending.requestId || pending.refreshing) return;
+ const request = backgroundOperations.find(
+ (operation) => Number(operation?.Requests?.id) === pending.requestId
+ );
+ const status = request?.Requests?.request_status;
+ if (!isOperationTerminal(status)) return;
+
+ if (status === "COMPLETED") {
+ setPendingAgents((current) => ({
+ ...current,
+ [pending.agent.id]: { ...pending, refreshing: true },
+ }));
+ void cachedServiceApi
+ .fetchAllServiceComponents(clusterName, true)
+ .finally(() => removePendingAgent(pending.agent.id));
+ } else {
+ removePendingAgent(pending.agent.id);
+ showFailure(pending, new Error(`The background request ended with status ${status}.`));
+ }
+ });
+ }, [
+ backgroundOperations,
+ clusterName,
+ pendingAgents,
+ removePendingAgent,
+ showFailure,
+ ]);
+
+ if (!masterSlaveClientsData) {
+ return <Spinner animation="border" size="sm" />;
+ }
+
+ if (agents.length === 0) {
+ return <div className="text-muted">No Flume agents are available.</div>;
+ }
+
+ return (
+ <Table responsive hover size="sm" className="mb-0">
+ <thead>
+ <tr>
+ <th>Host</th>
+ <th>Agent</th>
+ <th>Status</th>
+ </tr>
+ </thead>
+ <tbody>
+ {agents.map((agent) => {
+ const isPending = Boolean(pendingAgents[agent.id]);
+ const status = isPending ? "Pending" : displayStatus(agent.status);
+ return (
+ <tr key={agent.id}>
+ <td>{agent.hostName}</td>
+ <td>{agent.name}</td>
+ <td>
+ {canStartStop ? (
+ <Dropdown>
+ <Dropdown.Toggle
+ size="sm"
+ variant="light"
+ disabled={isPending}
+ aria-label={`Actions for Flume agent ${agent.name} on ${agent.hostName}`}
+ >
+ {isPending && <Spinner animation="border" size="sm" className="me-1" />}
+ {status}
+ </Dropdown.Toggle>
+ <Dropdown.Menu>
+ <Dropdown.Item
+ disabled={!canStartFlumeAgent(agent.status)}
+ onClick={() => confirmCommand(agent, "start")}
+ >
+ Start Agent
+ </Dropdown.Item>
+ <Dropdown.Item
+ disabled={!canStopFlumeAgent(agent.status)}
+ onClick={() => confirmCommand(agent, "stop")}
+ >
+ Stop Agent
+ </Dropdown.Item>
+ </Dropdown.Menu>
+ </Dropdown>
+ ) : status}
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </Table>
+ );
+}
+
+export default FlumeSummary;
diff --git a/ambari-web/latest/src/screens/Services/ServiceComponents.tsx b/ambari-web/latest/src/screens/Services/ServiceComponents.tsx
index 5ee1c161dc..52b13af188 100644
--- a/ambari-web/latest/src/screens/Services/ServiceComponents.tsx
+++ b/ambari-web/latest/src/screens/Services/ServiceComponents.tsx
@@ -41,6 +41,7 @@ import { useNavigate } from "react-router-dom";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import Tooltip from "../../components/Tooltip";
import { getComponentAlerts } from "./alertUtils";
+import FlumeSummary from "./FlumeSummary";
// Helper function to get component display name for alert modal titles
const getComponentDisplayName = (componentName: string): string => {
@@ -3859,6 +3860,8 @@ function ServiceComponents({
return <TRINOGATEWAYSummary alerts={alerts} />;
case "pinot":
return <PINOTSummary alerts={alerts} />;
+ case "flume":
+ return <FlumeSummary />;
default:
return <></>;
diff --git a/ambari-web/latest/src/screens/Services/ServiceDashboard.tsx b/ambari-web/latest/src/screens/Services/ServiceDashboard.tsx
index 38ae86efe9..27d86cbef6 100644
--- a/ambari-web/latest/src/screens/Services/ServiceDashboard.tsx
+++ b/ambari-web/latest/src/screens/Services/ServiceDashboard.tsx
@@ -18,7 +18,7 @@
import { Col, Row, Tab, Tabs } from "react-bootstrap";
import ServiceSummary from "./ServiceSummary";
-import { useNavigate, useParams, useLocation } from "react-router-dom";
+import { useNavigate, useParams } from "react-router-dom";
import "./styles/services.scss";
import ServiceConfigs from "../ServiceConfigs";
import { Actions } from "./Actions";
@@ -30,6 +30,7 @@ import Heatmaps from "../Heatmaps";
import { useAuth } from "../../hooks/useAuth";
import AuthGuard from "../../components/AuthGuard";
import RestartWarning from "./RestartWarning";
+import { resolveServiceNavigation } from "../../Utils/serviceNavigation";
enum TabNames {
SUMMARY = "summary",
@@ -38,6 +39,33 @@ enum TabNames {
METRICS = "metrics",
}
+const serviceTabs: Record<string, string[]> = {
+ HDFS: ["summary", "heatmaps", "configs", "metrics"],
+ YARN: ["summary", "heatmaps", "configs", "metrics"],
+ HIVE: ["summary", "configs"],
+ KAFKA: ["summary", "configs"],
+ ZOOKEEPER: ["summary", "configs"],
+ HBASE: ["summary", "heatmaps", "configs", "metrics"],
+ ATLAS: ["summary", "configs"],
+ RANGER: ["summary", "configs"],
+ RANGER_KMS: ["summary", "configs"],
+ SOLR: ["summary", "configs"],
+ FLUME: ["summary", "configs"],
+ AMBARI_METRICS: ["summary", "configs", "metrics"],
+ AMBARI_INFRA_SOLR: ["summary", "configs"],
+ LIVY: ["summary", "configs"],
+ TEZ: ["summary", "configs"],
+ KERBEROS: ["summary", "configs"],
+ MAPREDUCE2: ["summary", "configs"],
+ SQOOP: ["summary", "configs"],
+ SPARK3: ["summary", "configs"],
+ KYUUBI: ["summary", "configs"],
+ TRINO: ["summary", "configs"],
+ TRINO_GATEWAY: ["summary", "configs"],
+ SSM: ["summary", "configs"],
+ PINOT: ["summary", "configs"],
+};
+
function ServiceDashboard({
serviceName: serviceNameProps,
}: {
@@ -45,56 +73,14 @@ function ServiceDashboard({
}) {
// Authorization hooks - implementing Ember.js hasConfigTab logic
const { havePermissions } = useAuth();
- const { upgradeState } = useContext(AppContext);
-
- const configTabsUpgradeBlocked = [
- "IN_PROGRESS",
- "PENDING",
- "HOLDING_FAILED",
- "HOLDING_TIMEDOUT",
- "HOLDING",
- ].includes(upgradeState);
-
// Check CLUSTER.VIEW_CONFIGS permission like in Ember.js ui/app/views/main/service/item.js
- const hasConfigTab =
- havePermissions("CLUSTER.VIEW_CONFIGS") &&
- !configTabsUpgradeBlocked &&
- !upgradeState?.toLowerCase()?.includes("holding");
- const serviceTabs: { [key: string]: string[] } = {
- HDFS: ["summary", "heatmaps", "configs", "metrics"],
- YARN: ["summary", "heatmaps", "configs", "metrics"],
- HIVE: ["summary", "configs"],
- KAFKA: ["summary", "configs"],
- ZOOKEEPER: ["summary", "configs"],
- HBASE: ["summary", "heatmaps", "configs", "metrics"],
- ATLAS: ["summary", "configs"],
- RANGER: ["summary", "configs"],
- RANGER_KMS: ["summary", "configs"],
- SOLR: ["summary", "configs"],
- FLUME: ["summary", "configs"],
- AMBARI_METRICS: ["summary", "configs", "metrics"],
- AMBARI_INFRA_SOLR: ["summary", "configs"],
- LIVY: ["summary", "configs"],
- TEZ: ["summary", "configs"],
- KERBEROS: ["summary", "configs"],
- MAPREDUCE2: ["summary", "configs"],
- SQOOP: ["summary", "configs"],
- SPARK3: ["summary", "configs"],
- KYUUBI: ["summary", "configs"],
- TRINO: ["summary", "configs"],
- TRINO_GATEWAY: ["summary", "configs"],
- SSM: ["summary", "configs"],
- PINOT: ["summary", "configs"],
- };
-
+ const hasConfigTab = havePermissions("CLUSTER.VIEW_CONFIGS");
const { serviceName: serviceNameParams } = useParams();
const serviceName = serviceNameParams || serviceNameProps;
const { tabName } = useParams();
- const [selectedTab, setSelectedTab] = useState(tabName);
+ const [selectedTab, setSelectedTab] = useState(tabName || TabNames.SUMMARY);
const { services, clusterName } = useContext(AppContext);
- const selectedServices = map(services, "ServiceInfo.service_name");
const navigate = useNavigate();
- const location = useLocation();
useEffect(() => {
// Don't run URL replacement logic if services are still loading
@@ -102,32 +88,31 @@ function ServiceDashboard({
if (!services || services.length === 0) {
return;
}
+ const selectedServices = map(services, "ServiceInfo.service_name");
- if (
- serviceNameParams &&
- !selectedServices.includes(serviceNameParams) &&
- location.pathname.includes(serviceNameParams)
- ) {
- if (clusterName) {
- navigate(
- location.pathname.replace(serviceNameParams, selectedServices?.[0])
- );
- } else {
- navigate("/installer/step0");
- }
- } else {
- if (!selectedTab) {
- setSelectedTab(TabNames.SUMMARY);
- }
- if (
- serviceName &&
- selectedTab &&
- !serviceTabs[serviceName.toUpperCase()]?.includes(selectedTab)
- ) {
- setSelectedTab(TabNames.SUMMARY);
- }
+ const selection = resolveServiceNavigation({
+ availableTabs: serviceTabs,
+ canViewConfigs: hasConfigTab,
+ installedServices: selectedServices,
+ requestedService: serviceName,
+ requestedTab: tabName,
+ });
+ setSelectedTab(selection.selectedTab);
+
+ if (serviceNameParams && selection.redirectPath) {
+ navigate(clusterName ? selection.redirectPath : "/installer/step0", {
+ replace: true,
+ });
}
- }, [serviceName, serviceNameParams, location, services]); // Add services to dependencies
+ }, [
+ clusterName,
+ hasConfigTab,
+ navigate,
+ serviceName,
+ serviceNameParams,
+ services,
+ tabName,
+ ]);
return (
<div className="p-4">
@@ -137,7 +122,8 @@ function ServiceDashboard({
id="service-tabs"
className="ambari-tabs"
activeKey={selectedTab}
- onSelect={(tab: any) => {
+ onSelect={(tab) => {
+ if (!tab) return;
navigate(`/main/services/${serviceName}/${tab}`);
setSelectedTab(tab);
}}
diff --git a/ambari-web/latest/src/screens/Services/reassign/Step4.tsx b/ambari-web/latest/src/screens/Services/reassign/Step4.tsx
index f8efba142d..f60f699d0e 100755
--- a/ambari-web/latest/src/screens/Services/reassign/Step4.tsx
+++ b/ambari-web/latest/src/screens/Services/reassign/Step4.tsx
@@ -18,13 +18,12 @@
import { useContext, useEffect, useState } from "react";
import { useParams } from "react-router-dom";
-import { Alert } from "react-bootstrap";
+import { Alert, Button } from "react-bootstrap";
import { ReassignContext } from "./store/context";
import { ActionTypes } from "./store/types";
import WizardFooter from "../../../components/StepWizard/WizardFooter";
import {
componentsWithCheckDBStep,
- componentsWithManualCommands,
reassignSteps,
relatedServicesMap,
serviceToConfigSiteMap,
@@ -49,6 +48,8 @@ import OperationsProgress from "../../../components/OperationsProgress";
import InvalidKDCPopup from "../../Kerberos/InvalidKdcPopup";
import KerberosApi from "../../../api/kerberosApi";
import useKDCSessionState from "../../../hooks/useKDCSessionState";
+import modalManager from "../../../store/ModalManager";
+import { isMissingHostComponentError } from "../../../Utils/reassignValidation";
interface ReassignData {
component_name: string;
@@ -67,14 +68,13 @@ function Step4() {
state,
dispatch,
flushStateToDb,
+ hasManualCommands,
stepWizardUtilities: { currentStep, handleNextImperitive, jumpToStep },
} = useContext(ReassignContext);
const installedServices = map(services, "ServiceInfo.service_name");
// Check if this is the final step (no manual commands)
- const isLastStep = !componentsWithManualCommands.includes(
- componentName || ""
- );
+ const isLastStep = !hasManualCommands;
// State management
const [tasks, setTasks] = useState<any[]>([]);
@@ -89,6 +89,8 @@ function Step4() {
const { getKDCSessionState } = useKDCSessionState(null);
const [showInvalidKDCPopup, setShowInvalidKDCPopup] = useState(false);
const [stepOperations, setStepOperations] = useState<any>([]);
+ const [rollbackInProgress, setRollbackInProgress] = useState(false);
+ const [rollbackError, setRollbackError] = useState("");
const assignMastersData = getStepData(
state,
@@ -230,9 +232,7 @@ function Step4() {
service_id: getServiceForComponent(componentName || ""),
sourceHost: sourceHost,
targetHost: targetHost,
- hasManualSteps: componentsWithManualCommands.includes(
- componentName || ""
- ),
+ hasManualSteps: hasManualCommands,
};
};
@@ -1330,6 +1330,39 @@ function Step4() {
return await Promise.all(requests);
};
+ const putTargetHostComponentsInMaintenanceMode = async () => {
+ const reassignData = getReassignData();
+ await Promise.all(
+ hostComponents.map((component) =>
+ HostsApi.updateHostComponentPassiveState(
+ clusterName,
+ reassignData.targetHost,
+ component,
+ { context: undefined, passive_state: "ON" }
+ )
+ )
+ );
+ };
+
+ const deleteTargetHostComponents = async () => {
+ const reassignData = getReassignData();
+ await Promise.all(
+ hostComponents.map(async (component) => {
+ try {
+ await HostsApi.deleteHostComponent(
+ clusterName,
+ reassignData.targetHost,
+ component
+ );
+ } catch (error) {
+ if (!isMissingHostComponentError(error)) {
+ throw error;
+ }
+ }
+ })
+ );
+ };
+
const configureMySqlServer = async () => {
const reassignData = getReassignData();
let hostname = "";
@@ -1562,8 +1595,8 @@ function Step4() {
const requestResponse = await RequestApi.getTaskId(checkDBRequestId);
if (requestResponse?.items?.[0]?.Tasks?.id) {
const taskResponse = await getDBConnTaskInfo(
- requestResponse.items[0].Tasks.id,
- checkDBRequestId
+ checkDBRequestId,
+ requestResponse.items[0].Tasks.id
);
return taskResponse;
}
@@ -1606,10 +1639,14 @@ function Step4() {
}
if (/PENDING|QUEUED|IN_PROGRESS/.test(task.status)) {
- setTimeout(async () => {
- const result = await getDBConnTaskInfo(checkDBRequestId, checkDBTaskId);
- return result;
- }, 3000);
+ return new Promise((resolve, reject) => {
+ setTimeout(() => {
+ getDBConnTaskInfo(checkDBRequestId, checkDBTaskId).then(
+ resolve,
+ reject
+ );
+ }, 3000);
+ });
}
};
@@ -1706,6 +1743,7 @@ function Step4() {
const operations = tasks.map((task) => ({
id: task.id,
label: task.title,
+ command: task.command,
skippable: false,
callback: async () => {
try {
@@ -1759,6 +1797,49 @@ function Step4() {
return operations;
}
+ const rollbackDatabaseMove = async () => {
+ setRollbackInProgress(true);
+ setRollbackError("");
+ try {
+ await putTargetHostComponentsInMaintenanceMode();
+ await deleteTargetHostComponents();
+ await cleanMySqlServer();
+ await configureMySqlServer();
+ await startRequiredServices();
+ await flushStateToDb("complete");
+ const serviceName = getServiceForComponent(componentName || "");
+ window.location.href = `/#/main/services/${serviceName}/summary`;
+ } catch (error: unknown) {
+ const fallbackMessage =
+ error instanceof Error
+ ? error.message
+ : "The rollback operation failed.";
+ setRollbackError(
+ get(
+ error,
+ "response.data.message",
+ fallbackMessage
+ )
+ );
+ } finally {
+ setRollbackInProgress(false);
+ }
+ };
+
+ const confirmDatabaseRollback = () => {
+ modalManager.show({
+ modalTitle: "Rollback Component Move",
+ modalBody:
+ "The database connection test failed. Remove the component from the target host, restore the database service configuration, and restart the affected services?",
+ successCallback: () => {
+ modalManager.hide();
+ void rollbackDatabaseMove();
+ },
+ onClose: () => modalManager.hide(),
+ options: { okButtonText: "ROLLBACK" },
+ });
+ };
+
const handleNext = async () => {
if (isLastStep) {
// If this is the final step, complete the wizard and redirect
@@ -1848,6 +1929,23 @@ function Step4() {
<Spinner />
)}
+ {stepOperations.some(
+ (operation: { command?: string; status?: string }) =>
+ operation.command === "testDBConnection" &&
+ operation.status === "FAILED"
+ ) ? (
+ <div className="mt-3">
+ {rollbackError ? <Alert variant="danger">{rollbackError}</Alert> : null}
+ <Button
+ variant="danger"
+ disabled={rollbackInProgress}
+ onClick={confirmDatabaseRollback}
+ >
+ {rollbackInProgress ? "ROLLING BACK" : "ROLLBACK"}
+ </Button>
+ </div>
+ ) : null}
+
<WizardFooter
step={currentStep}
isNextEnabled={completionStatus}
diff --git a/ambari-web/latest/src/screens/Services/reassign/Step5.tsx b/ambari-web/latest/src/screens/Services/reassign/Step5.tsx
index 1d0023cd4f..f5742e79fa 100644
--- a/ambari-web/latest/src/screens/Services/reassign/Step5.tsx
+++ b/ambari-web/latest/src/screens/Services/reassign/Step5.tsx
@@ -35,6 +35,7 @@ import ConfigsApi from "../../../api/configsApi";
import { AppContext } from "../../../store/context";
import { ServiceContext } from "../../../store/ServiceContext";
import { showConfirmationPopup } from "../../Hosts/utils";
+import { getDatabaseManualCommands } from "../../../Utils/reassignManualCommands";
function Step5() {
const { componentName } = useParams<{ componentName: string }>();
@@ -166,12 +167,24 @@ function Step5() {
const targetHost = reassignHosts.target;
let hdfsUser = "hdfs";
+ let hadoopGroup = "hadoop";
get(configs, "items.[0].configurations", []).forEach((config: any) => {
if (config.type === "hadoop-env") {
hdfsUser = config.properties["hdfs_user"] || hdfsUser;
+ hadoopGroup = config.properties["user_group"] || hadoopGroup;
}
});
+ const databaseSteps = getDatabaseManualCommands({
+ componentName: componentName || "",
+ groupName: hadoopGroup,
+ sourceHost,
+ targetHost,
+ });
+ if (databaseSteps) {
+ return { steps: databaseSteps };
+ }
+
if (componentName === "NAMENODE") {
if (isHaEnabled) {
// HA-enabled NameNode move
diff --git a/ambari-web/latest/src/screens/Services/reassign/ValidateMove.tsx b/ambari-web/latest/src/screens/Services/reassign/ValidateMove.tsx
index 1c0d322225..5b9f18d3d4 100644
--- a/ambari-web/latest/src/screens/Services/reassign/ValidateMove.tsx
+++ b/ambari-web/latest/src/screens/Services/reassign/ValidateMove.tsx
@@ -17,7 +17,7 @@
*/
-import {useState,useContext,useEffect } from "react";
+import { useContext, useEffect, useMemo, useState } from "react";
import useStepWizard from "../../../hooks/useStepWizard";
import Spinner from "../../../components/Spinner";
import { ReassignProvider, ReassignContext } from "./store/context";
@@ -25,7 +25,7 @@ import StepWizard from "../../../components/StepWizard";
import Modal from "../../../components/Modal";
import ClusterApi from "../../../api/clusterApi";
import { useParams } from "react-router-dom";
-import { componentsWithManualCommands, reassignSteps } from "./constants";
+import { reassignSteps } from "./constants";
import { ServiceContext } from "../../../store/ServiceContext";
import { ActionTypes } from "./store/types";
import Step1 from "./Step1";
@@ -34,6 +34,16 @@ import Step3 from "./Step3";
import Step4 from "./Step4";
import Step5 from "./Step5";
import Step6 from "./Step6";
+import { AppContext } from "../../../store/context";
+import { serviceNameModelMapping } from "../../../constants";
+import { getReassignValidationErrors } from "../../../Utils/reassignValidation";
+import ConfigsApi from "../../../api/configsApi";
+import { Alert, Button } from "react-bootstrap";
+import {
+ getOozieJdbcDriver,
+ hasReassignManualCommands,
+} from "../../../Utils/reassignManualCommands";
+import { Step } from "../../../types/StepWizard";
// Component to initialize the component name in the store
const ComponentNameInitializer: React.FC<{ componentName: string | undefined }> = ({ componentName }) => {
@@ -51,19 +61,185 @@ const ComponentNameInitializer: React.FC<{ componentName: string | undefined }>
return null;
};
+function getSteps(componentName: string | undefined, hasManualCommands: boolean) {
+ if (!componentName) {
+ return {};
+ }
+
+ const inferredSteps: Record<number, Step & { name: reassignSteps }> = {
+ 1: {
+ label: "Get Started",
+ completed: false,
+ Component: <Step1 />,
+ canGoBack: false,
+ isNextEnabled: false,
+ name: reassignSteps.GET_STARTED,
+ },
+ 2: {
+ label: "Assign Masters",
+ completed: false,
+ Component: <Step2 />,
+ canGoBack: true,
+ isNextEnabled: false,
+ name: reassignSteps.ASSIGN_MASTER,
+ },
+ 3: {
+ label: "Review",
+ completed: false,
+ Component: <Step3 />,
+ canGoBack: true,
+ isNextEnabled: false,
+ name: reassignSteps.REVIEW,
+ nextLabel: "DEPLOY",
+ },
+ 4: {
+ label: "Configure Component",
+ completed: false,
+ Component: <Step4 />,
+ canGoBack: false,
+ isNextEnabled: true,
+ name: reassignSteps.CONFIGURE_COMPONENT,
+ nextLabel: hasManualCommands ? "Next" : "Complete",
+ },
+ };
+
+ if (hasManualCommands) {
+ inferredSteps[5] = {
+ label: "Manual Commands",
+ completed: false,
+ Component: <Step5 />,
+ canGoBack: true,
+ isNextEnabled: false,
+ name: reassignSteps.MANUAL_COMMANDS,
+ nextLabel: "Next",
+ };
+ inferredSteps[6] = {
+ label: "Start and Test Services",
+ completed: false,
+ Component: <Step6 />,
+ canGoBack: true,
+ isNextEnabled: false,
+ name: reassignSteps.START_AND_TEST_SERVICES,
+ nextLabel: "Complete",
+ };
+ }
+
+ return inferredSteps;
+}
+
+function MoveWizard({
+ componentName,
+ hasManualCommands,
+}: {
+ componentName: string | undefined;
+ hasManualCommands: boolean;
+}) {
+ const stepWizardUtilities = useStepWizard(
+ getSteps(componentName, hasManualCommands),
+ 1
+ );
+
+ return (
+ <ReassignProvider
+ stepWizardUtilities={stepWizardUtilities}
+ hasManualCommands={hasManualCommands}
+ >
+ <ComponentNameInitializer componentName={componentName} />
+ <StepWizard wizardUtilities={stepWizardUtilities} />
+ </ReassignProvider>
+ );
+}
+
function ValidateMove({
serviceName: serviceNameProp,
}: {
serviceName: string;
}) {
const { componentName } = useParams();
- const { allServiceModels } = useContext(ServiceContext);
- const [canStartMove] = useState(true);
- const [validationErrors] = useState<string[]>([]);
- const [checkingForMovement] = useState(false);
- //@ts-ignore
- const isHAEnabled = allServiceModels?.["hdfs"]?.isNameNodeHaEnabled || false;
- const stepWizardUtilities = useStepWizard(getSteps(), 1);
+ const { allModelsLoaded, allServiceModels } = useContext(ServiceContext);
+ const { allHostNames, clusterName, isAppLoaded, serviceComponentInfo } =
+ useContext(AppContext);
+ const [oozieEligibility, setOozieEligibility] = useState<{
+ componentName?: string;
+ hasManualCommands?: boolean;
+ error?: string;
+ }>({});
+ const [oozieLoadAttempt, setOozieLoadAttempt] = useState(0);
+ const isOozie = componentName === "OOZIE_SERVER";
+ const hasCurrentOozieEligibility =
+ oozieEligibility.componentName === componentName;
+ const manualCommandsLoading =
+ isOozie &&
+ (!hasCurrentOozieEligibility ||
+ (oozieEligibility.hasManualCommands === undefined &&
+ !oozieEligibility.error));
+ const manualCommandsError = hasCurrentOozieEligibility
+ ? oozieEligibility.error
+ : undefined;
+ const hasManualCommands = isOozie
+ ? oozieEligibility.hasManualCommands === true
+ : hasReassignManualCommands(componentName);
+ const checkingForMovement =
+ !isAppLoaded || !allModelsLoaded || manualCommandsLoading;
+
+ useEffect(() => {
+ if (!isOozie || !clusterName) {
+ return;
+ }
+
+ let cancelled = false;
+ setOozieEligibility({ componentName });
+ ConfigsApi.getConfigValues(clusterName, "OOZIE")
+ .then((response) => {
+ if (!cancelled) {
+ setOozieEligibility({
+ componentName,
+ hasManualCommands: hasReassignManualCommands(
+ componentName,
+ getOozieJdbcDriver(response)
+ ),
+ });
+ }
+ })
+ .catch((error) => {
+ if (!cancelled) {
+ setOozieEligibility({
+ componentName,
+ error:
+ error instanceof Error
+ ? error.message
+ : "Could not load the current Oozie database configuration.",
+ });
+ }
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [clusterName, componentName, isOozie, oozieLoadAttempt]);
+ const validationErrors = useMemo(
+ () =>
+ checkingForMovement
+ ? []
+ : getReassignValidationErrors({
+ componentName,
+ serviceName: serviceNameProp,
+ allHostNames,
+ serviceComponentInfo,
+ serviceModel:
+ allServiceModels[serviceNameModelMapping[serviceNameProp]],
+ }),
+ [
+ allHostNames,
+ allServiceModels,
+ checkingForMovement,
+ componentName,
+ serviceComponentInfo,
+ serviceNameProp,
+ ]
+ );
+ const canStartMove =
+ !checkingForMovement && !manualCommandsError && validationErrors.length === 0;
const [showModal, setShowModal] = useState(true);
const getModalBodyContent = () => {
if (checkingForMovement) {
@@ -73,6 +249,20 @@ function ValidateMove({
</div>
);
}
+ if (manualCommandsError) {
+ return (
+ <Alert variant="danger">
+ <div>{manualCommandsError}</div>
+ <Button
+ className="mt-3"
+ variant="outline-danger"
+ onClick={() => setOozieLoadAttempt((attempt) => attempt + 1)}
+ >
+ Retry
+ </Button>
+ </Alert>
+ );
+ }
if (validationErrors.length) {
return (
<>
@@ -86,91 +276,12 @@ function ValidateMove({
);
}
return (
- <ReassignProvider stepWizardUtilities={stepWizardUtilities}>
- <ComponentNameInitializer componentName={componentName} />
- <StepWizard wizardUtilities={stepWizardUtilities} />
- </ReassignProvider>
+ <MoveWizard
+ componentName={componentName}
+ hasManualCommands={hasManualCommands}
+ />
);
};
- function getSteps(){
- if (componentName) {
- const hasManualCommands = componentsWithManualCommands.includes(componentName);
-
- const inferredSteps:any = {
- 1: {
- label: "Get Started",
- completed: false,
- Component: <Step1 />,
- canGoBack: false,
- isNextEnabled: false,
- name: reassignSteps.GET_STARTED,
- },
- 2: {
- label: "Assign Masters",
- completed: false,
- Component: <Step2/>,
- canGoBack: true,
- isNextEnabled: false,
- name: reassignSteps.ASSIGN_MASTER,
- },
- 3: {
- label: "Review",
- completed: false,
- Component:<Step3/>,
- canGoBack: true,
- isNextEnabled: false,
- name: reassignSteps.REVIEW,
- nextLabel: "DEPLOY",
- },
- 4: {
- label: "Configure Component",
- completed: false,
- Component: <Step4 />,
- canGoBack: false,
- isNextEnabled: true,
- name: reassignSteps.CONFIGURE_COMPONENT,
- // Set nextLabel to "Complete" if this is the final step
- nextLabel: hasManualCommands ? "Next" : "Complete",
- },
- };
-
- if(hasManualCommands){
- inferredSteps[5]={
- label: "Manual Commands",
- completed: false,
- Component: <Step5 />,
- canGoBack: true,
- isNextEnabled: false,
- name: reassignSteps.MANUAL_COMMANDS,
- nextLabel: "Next",
- }
- inferredSteps[6]={
- label: "Start and Test Services",
- completed: false,
- Component: <Step6 />,
- canGoBack: true,
- isNextEnabled: false,
- name: reassignSteps.START_AND_TEST_SERVICES,
- nextLabel: "Complete",
- }
-
- // Only add Step 7 for NAMENODE with HA enabled
- // if (componentName === 'NAMENODE' && isHAEnabled) {
- // inferredSteps[7]={
- // label: "Finalize Move",
- // completed: false,
- // Component: <Step7 />,
- // canGoBack: true,
- // isNextEnabled: false,
- // name: reassignSteps.FINALIZE_MOVE,
- // nextLabel: "Complete",
- // }
- // }
- }
-
- return inferredSteps
- }
- }
return (
<>
{showModal ? (
diff --git a/ambari-web/latest/src/screens/Services/reassign/index.tsx b/ambari-web/latest/src/screens/Services/reassign/index.tsx
index 46edfde239..29dd2e3af6 100644
--- a/ambari-web/latest/src/screens/Services/reassign/index.tsx
+++ b/ambari-web/latest/src/screens/Services/reassign/index.tsx
@@ -26,6 +26,7 @@ import { mastersNotShown, serviceNameModelMapping } from "../../../constants";
import { camelCase, map, startCase, filter } from "lodash";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faShuffle } from "@fortawesome/free-solid-svg-icons";
+import { getComponentHostNames } from "../../../Utils/reassignValidation";
type ReassignComponentProps = {
serviceName: string;
@@ -107,6 +108,19 @@ function ReassignComponent({
{allMasters?.length && !isMappingOnly
? allMasters.map((master: any) => (
<DropdownItem
+ key={master}
+ disabled={
+ allHostNames.length > 0 &&
+ allHostNames.every((hostName) => {
+ const component = allServiceModels[
+ serviceNameModelMapping[serviceNameProp]
+ ]?.masterComponents?.find(
+ (item: { componentName?: string }) =>
+ item.componentName === master
+ );
+ return getComponentHostNames(component).includes(hostName);
+ })
+ }
onClick={() => {
navigate(`/main/service/reassign/${master}/step1`);
}}
diff --git a/ambari-web/latest/src/screens/Services/reassign/store/context.tsx b/ambari-web/latest/src/screens/Services/reassign/store/context.tsx
index 119faebbee..352a45bab6 100644
--- a/ambari-web/latest/src/screens/Services/reassign/store/context.tsx
+++ b/ambari-web/latest/src/screens/Services/reassign/store/context.tsx
@@ -30,18 +30,21 @@ interface ReassignContextProps {
dispatch: Dispatch<Action>;
stepWizardUtilities?: any;
flushStateToDb?: any;
+ hasManualCommands: boolean;
}
export const ReassignContext = createContext<ReassignContextProps>({
state: initialState,
dispatch: () => undefined,
flushStateToDb: () => undefined,
+ hasManualCommands: false,
});
export const ReassignProvider: React.FC<{
stepWizardUtilities: any;
+ hasManualCommands: boolean;
children: React.ReactNode;
-}> = ({ stepWizardUtilities, children }) => {
+}> = ({ stepWizardUtilities, hasManualCommands, children }) => {
const [state, dispatch] = useReducer(reducer, initialState);
const [currStepData, setCurrStepData] = useState({});
const isDataPersisted = useRef(false);
@@ -196,7 +199,13 @@ export const ReassignProvider: React.FC<{
return (
<ReassignContext.Provider
- value={{ state, dispatch, stepWizardUtilities, flushStateToDb }}
+ value={{
+ state,
+ dispatch,
+ stepWizardUtilities,
+ flushStateToDb,
+ hasManualCommands,
+ }}
>
{children}
</ReassignContext.Provider>
diff --git a/ambari-web/latest/src/store/ServiceContext.tsx b/ambari-web/latest/src/store/ServiceContext.tsx
index bc929d0a1c..9ed8bae806 100644
--- a/ambari-web/latest/src/store/ServiceContext.tsx
+++ b/ambari-web/latest/src/store/ServiceContext.tsx
@@ -48,6 +48,7 @@ import PinotService from "../models/pinot.ts";
interface ServiceContextType {
allServiceModels: { [key: string]: any };
+ allModelsLoaded: boolean;
serviceModels: { [key: string]: any };
updateRegistry: Function;
polledHostComponentsData: {};
@@ -58,6 +59,7 @@ interface ServiceContextType {
export const ServiceContext = React.createContext<ServiceContextType>({
allServiceModels: {},
+ allModelsLoaded: false,
serviceModels: {},
updateRegistry: () => {},
polledHostComponentsData: () => {},
@@ -453,6 +455,7 @@ const ServiceProvider: React.FC<ServiceProviderProps> = ({ children }) => {
<ServiceContext.Provider
value={{
allServiceModels,
+ allModelsLoaded,
serviceModels: allServiceModels,
updateRegistry,
polledHostComponentsData,
diff --git a/dev-support/ambari-ai/README.md b/dev-support/ambari-ai/README.md
index 3f5a74e107..bb9a3c88be 100644
--- a/dev-support/ambari-ai/README.md
+++ b/dev-support/ambari-ai/README.md
@@ -80,7 +80,8 @@ Base: trunk
The summary is read from JIRA unless `--summary` is supplied. The branch is
created from `origin/trunk` by default. Use `--base` and `--base-ref` for a
-different target.
+different target. The generated pull request body starts with a link to the
+corresponding ASF JIRA issue.
## Approve and merge
diff --git a/dev-support/ambari-ai/ambari_ai.py b/dev-support/ambari-ai/ambari_ai.py
index 2e881ab583..09f09fc158 100755
--- a/dev-support/ambari-ai/ambari_ai.py
+++ b/dev-support/ambari-ai/ambari_ai.py
@@ -430,6 +430,7 @@ def markdown_to_jira(value: str) -> str:
def build_pull_request_body(
+ issue_key: str,
changes: str,
test_result: str,
test_command: Optional[str] = None,
@@ -442,6 +443,9 @@ def build_pull_request_body(
test_parts.extend(["", "\n".join(item.strip() for item in evidence)])
return "\n".join([
+ "Issue: [{}]({}/browse/{})".format(
+ issue_key, DEFAULT_JIRA_URL, issue_key),
+ "",
"## What changes were proposed in this pull request?",
"",
changes.strip(),
@@ -556,7 +560,7 @@ def command_pr_create(args: argparse.Namespace) -> Dict[str, Any]:
created = False
else:
body = build_pull_request_body(
- changes, test_result, args.test_command, args.evidence)
+ issue_key, changes, test_result, args.test_command, args.evidence)
pull = github.create_pull_request(title, body, head, args.base, args.draft)
created = True
diff --git a/dev-support/ambari-ai/test_ambari_ai.py b/dev-support/ambari-ai/test_ambari_ai.py
index e5352ef1d8..739adf4a82 100644
--- a/dev-support/ambari-ai/test_ambari_ai.py
+++ b/dev-support/ambari-ai/test_ambari_ai.py
@@ -170,12 +170,19 @@ npm test
def test_pull_request_body_matches_repository_template(self):
body = ambari_ai.build_pull_request_body(
+ "AMBARI-26474",
"Fix TestAmbariServer initialization.",
"The affected test passed.",
"mvn test -Dpython.test.mask=TestAmbariServer.py",
["Before: failed", "After: passed"],
)
+ self.assertTrue(
+ body.startswith(
+ "Issue: [AMBARI-26474]"
+ "(https://issues.apache.org/jira/browse/AMBARI-26474)\n\n"
+ )
+ )
self.assertIn("## What changes were proposed in this pull request?", body)
self.assertIn("Fix TestAmbariServer initialization.", body)
self.assertIn("## How was this patch tested?", body)
diff --git a/docs/frontend-refactor/react-current/04-services-configs-gap.md b/docs/frontend-refactor/react-current/04-services-configs-gap.md
new file mode 100644
index 0000000000..662761ebf4
--- /dev/null
+++ b/docs/frontend-refactor/react-current/04-services-configs-gap.md
@@ -0,0 +1,427 @@
+<!---
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You 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.
+-->
+
+# React Services and Configs Comparison
+
+## Comparison Scope
+
+| Item | Value |
+| --- | --- |
+| Ember baseline | `ember-baseline/04-services-configs.md` |
+| React implementation | `ambari-web/latest`, Module 04 work based on `c01b54be258f04282e00403e7b77ee8054aab947` |
+| Feature IDs | 60 non-Metrics IDs from `SVC-NAV-001` through `SVC-MOVE-006` |
+| Review date | 2026-08-14 |
+| Metrics boundary | Service Metrics, Heatmaps, metric display data, Metrics APIs, and metric widgets are excluded |
+
+The audit compared the baseline with the actual `ambari-web/classic` implementation and the current React source. It also reverse-scanned the generated AJAX definitions and call sites, direct HTTP calls, browser network entry points, realtime channels, permissions, feature flags, and routes. The heuristic `generated/api-by-module/services-configs.md` inventory was treated as a candidate list, not an authoritative contract.
+
+The legacy `/main/services/:service_id/audit` outlet has no functional page and remains a placeholder. React is not required to add an Audit tab.
+
+## Initial Static Conclusion
+
+| Status | Count |
+| --- | ---: |
+| `STATICALLY_ALIGNED` | 1 |
+| `PARTIAL` | 50 |
+| `INCORRECT` | 6 |
+| `MISSING` | 3 |
+| Total | 60 |
+
+This table records the state before Module 04 implementation. A feature is not considered covered merely because a route or similarly named component exists. `STATICALLY_ALIGNED` still requires runtime validation against Ambari Server.
+
+## Post-Implementation Status
+
+`STATICALLY_ALIGNED` means the reviewed React behavior and focused executable evidence now match the classic contract, but the corresponding live scenario remains in the runtime acceptance matrix. `IMPROVED_PARTIAL` means this patch fixes identified defects while other parity work remains. `CROSS_MODULE_BOUNDARY` identifies behavior that cannot be completed without reconciling Module 03-owned Hosts code.
+
+| Final status | Count |
+| --- | ---: |
+| `STATICALLY_ALIGNED` | 26 |
+| `IMPROVED_PARTIAL` | 21 |
+| `UNCHANGED_PARTIAL` | 11 |
+| `CROSS_MODULE_BOUNDARY` | 2 |
+| `MISSING` | 0 |
+| Total | 60 |
+
+The written Ember baseline overstates `SVC-ALL-004`: the global action does not offer immediate versus rolling/scheduled execution. Classic `main/service.js#restartAllRequired` confirms and invokes `restart.staleConfigs` once; its AJAX definition sends one `POST /clusters/{cluster}/requests` with the stale-host-component predicate. Rolling selection belongs to the per-service Summary/Configs flows. The status and runtime matrix below follow the executable Classic source and generated AJA [...]
+
+| ID | Final status | Post-implementation evidence or remaining gap |
+| --- | --- | --- |
+| `SVC-NAV-001` | `STATICALLY_ALIGNED` | URL changes and Back/Forward update the selected tab; invalid services replace to the first installed service Summary, and invalid or unauthorized tabs replace to Summary without rewriting embedded wizard routes. |
+| `SVC-ALL-001` | `IMPROVED_PARTIAL` | Authorization, `enableAddDeleteServices`, conflicting-wizard/upgrade route gates, Add Service-owned cleanup, and provisioning-state behavior are fixed; full seven-step recovery remains runtime-required. |
+| `SVC-ALL-002` | `STATICALLY_ALIGNED` | Preserves the broad classic service PUT and now adds health eligibility, confirmation, background progress, rejection details, and Retry. |
+| `SVC-ALL-003` | `STATICALLY_ALIGNED` | Preserves the broad classic service PUT and now adds health eligibility, HDFS checkpoint/impact confirmation, background progress, rejection details, and Retry. |
+| `SVC-ALL-004` | `STATICALLY_ALIGNED` | Preserves Classic's single confirmed `restart.staleConfigs` POST for every stale host component and exposes request progress and Retry; no global rolling selector is added. |
+| `SVC-ALL-005` | `UNCHANGED_PARTIAL` | Cluster client download remains available, but popup-blocked browser behavior and the legacy outer-menu quirk require acceptance. |
+| `SVC-ACT-001` | `IMPROVED_PARTIAL` | Start/Stop permission gates are corrected for restart entries; complete action eligibility, schedule choices, and convergence remain partial. |
+| `SVC-ACT-002` | `IMPROVED_PARTIAL` | Service Check now requires `SERVICE.RUN_SERVICE_CHECK`; stack availability, result presentation, and retry still need broader coverage. |
+| `SVC-ACT-003` | `IMPROVED_PARTIAL` | The exact service maintenance PUT is asserted, success converges local state, and server failure exposes Retry; exhaustive component/alert convergence remains live-required. |
+| `SVC-ACT-004` | `IMPROVED_PARTIAL` | Restart entries now require `SERVICE.START_STOP`; stale filtering, rolling parameters, and progress remain partial. |
+| `SVC-ACT-005` | `IMPROVED_PARTIAL` | Delete Service now respects authorization, the feature flag, and conflicting-wizard state; dependency and recovery matrices remain incomplete. |
+| `SVC-ACT-006` | `IMPROVED_PARTIAL` | YARN queue refresh now requires `SERVICE.RUN_CUSTOM_COMMAND`; command availability and progress remain runtime-required. |
+| `SVC-ACT-007` | `IMPROVED_PARTIAL` | HDFS rebalance now requires `SERVICE.RUN_CUSTOM_COMMAND`; topology eligibility and recovery remain partial. |
+| `SVC-ACT-008` | `IMPROVED_PARTIAL` | HDFS/YARN service commands now use the semantic custom-command permission; stack/state coverage remains partial. |
+| `SVC-ACT-009` | `IMPROVED_PARTIAL` | Dynamic commands no longer inherit unrelated permissions; metadata scopes, parameters, and recovery remain partial. |
+| `SVC-ACT-010` | `IMPROVED_PARTIAL` | HA/Federation/Journal and Move entries/routes use semantic permissions and operation guards; all stack-specific conditions remain partial. |
+| `SVC-ACT-011` | `STATICALLY_ALIGNED` | Current-service all-client download now uses `SERVICE`; `SERVICE_COMPONENT` remains reserved for one component and cluster download uses `CLUSTER`. |
+| `SVC-SUM-001` | `UNCHANGED_PARTIAL` | Non-Metrics summary layouts still lack complete service-specific state, maintenance, restart, and distribution parity. |
+| `SVC-SUM-002` | `CROSS_MODULE_BOUNDARY` | Exact Hosts filtering and return-path behavior must be reconciled with Module 03 without editing its files here. |
+| `SVC-SUM-003` | `CROSS_MODULE_BOUNDARY` | Complete host-component actions depend on Module 03-owned eligibility and payload helpers; this branch records rather than duplicates them. |
+| `SVC-SUM-004` | `STATICALLY_ALIGNED` | Flume Summary discovers per-host handlers, gates state-valid Start/Stop by permission and wizard state, sends the exact handler PUT, tracks progress, refreshes, and exposes Retry. |
+| `SVC-SUM-005` | `IMPROVED_PARTIAL` | External links gain corrected descriptor/config/host resolution; separate Ambari View route/iframe parity remains incomplete. |
+| `SVC-QL-001` | `STATICALLY_ALIGNED` | Descriptor URL, visible/removed filtering, related-component discovery, and focused API evidence are aligned. |
+| `SVC-QL-002` | `STATICALLY_ALIGNED` | Deterministic tests cover `HTTP_ONLY`, `HTTPS_ONLY`, `EXIST`, `NOT_EXIST`, exact values, reversal, missing properties, and the Classic `hdfs-site/dfs.http.policy` fallback. |
+| `SVC-QL-003` | `STATICALLY_ALIGNED` | Component hosts are generalized and internal hostnames are resolved through the public-host API before URL generation. |
+| `SVC-QL-004` | `STATICALLY_ALIGNED` | Logged-in username and `${config-type/property-name}` placeholders are substituted with focused tests. |
+| `SVC-QL-005` | `STATICALLY_ALIGNED` | MapReduce configured-host reverse mapping and Oozie `STARTED` host filtering are implemented. |
+| `SVC-QL-006` | `UNCHANGED_PARTIAL` | HDFS/YARN/HBase Active/Standby selection exists but still requires exhaustive operational-state acceptance. |
+| `SVC-QL-007` | `STATICALLY_ALIGNED` | External anchors retain `_blank` plus `noreferrer`; all generated branches remain runtime-required. |
+| `SVC-CONFIG-001` | `UNCHANGED_PARTIAL` | Theme/category controls still require complete control-type and no-theme fallback acceptance. |
+| `SVC-CONFIG-002` | `UNCHANGED_PARTIAL` | Recommended/default/final/read-only metadata semantics remain incomplete across all controls. |
+| `SVC-CONFIG-003` | `UNCHANGED_PARTIAL` | Editing/recommendation/dependency/undo parity remains uneven between rows and widgets. |
+| `SVC-CONFIG-004` | `STATICALLY_ALIGNED` | Default saves await the request and send every property plus all non-empty attribute categories for each changed type. |
+| `SVC-CONFIG-005` | `STATICALLY_ALIGNED` | Navigation proceeds only after an awaited successful save; failure retains the blocker and edits, and refresh follows completion rather than a timer. |
+| `SVC-CONFIG-006` | `IMPROVED_PARTIAL` | Compare now requires `SERVICE.COMPARE_CONFIGS`; non-default history selection and read-only behavior remain runtime-required. |
+| `SVC-CONFIG-007` | `STATICALLY_ALIGNED` | Make Current requires `SERVICE.MODIFY_CONFIGS`, preserves the history-creating cluster PUT, and refreshes exact installed services with a corrected URL. |
+| `SVC-CONFIG-008` | `IMPROVED_PARTIAL` | Empty-string overrides are preserved; complete widget/row restore and recommendation parity remains partial. |
+| `SVC-CONFIG-009` | `IMPROVED_PARTIAL` | Restart entries use `SERVICE.START_STOP`; maintenance/state filters and rolling progress remain incomplete. |
+| `SVC-CONFIG-010` | `STATICALLY_ALIGNED` | Create, missing-ID, task-list, poll, terminal task, and non-zero DB check failures end Connecting and permit Retry. |
+| `SVC-CONFIG-011` | `STATICALLY_ALIGNED` | Single/bulk parsing validates trimmed keys, duplicates, existing entries, true line numbers, and extra `=` values; removed keys can be re-added and persisted deletion is omitted from the replacement payload. |
+| `CFG-GROUP-001` | `STATICALLY_ALIGNED` | Management now requires `SERVICE.MANAGE_CONFIG_GROUPS` in both selector and modal actions. |
+| `CFG-GROUP-002` | `IMPROVED_PARTIAL` | Membership uniqueness is enforced through clear-before-set ordering and save failures remain visible/retryable; create conflict acceptance remains. |
+| `CFG-GROUP-003` | `STATICALLY_ALIGNED` | Duplicate copies desired configs and description while intentionally leaving hosts empty; existing-name validation remains in the form. |
+| `CFG-GROUP-004` | `STATICALLY_ALIGNED` | Hosts can move directly between non-default groups, with atomic local state and two-phase clear/set server ordering, including swaps. |
+| `CFG-GROUP-005` | `STATICALLY_ALIGNED` | Delete returns hosts to Default locally, clears server membership before DELETE, and preserves the modal with an error for Retry. |
+| `CFG-GROUP-006` | `STATICALLY_ALIGNED` | Group properties and edit entry preserve the selected config group and version through the shared history selection path; focused history evidence covers group/version resolution. |
+| `SVC-ADD-001` | `IMPROVED_PARTIAL` | Entry and direct route now enforce permission, feature flag, upgrade, and conflicting-wizard policy; dependency/conflict validation remains broad. |
+| `SVC-ADD-002` | `UNCHANGED_PARTIAL` | Master cardinality, resource, installed-component, and ineligible-host matrices remain incomplete. |
+| `SVC-ADD-003` | `UNCHANGED_PARTIAL` | Slave/client retention and host eligibility remain incomplete. |
+| `SVC-ADD-004` | `UNCHANGED_PARTIAL` | Config recommendations, credentials, database/account tabs, and recovery remain incomplete. |
+| `SVC-ADD-005` | `UNCHANGED_PARTIAL` | Review completeness and no-mutation acceptance remain outstanding. |
+| `SVC-ADD-006` | `IMPROVED_PARTIAL` | Direct route ownership is guarded and persisted cleanup is corrected; exact deploy ordering and partial-failure recovery remain runtime-required. |
+| `SVC-ADD-007` | `STATICALLY_ALIGNED` | Add Service completion no longer writes Installer-only `Clusters.provisioning_state=INSTALLED`; Cluster Creation behavior is preserved. |
+| `SVC-ADD-008` | `IMPROVED_PARTIAL` | Add Service owns cancel cleanup, invalidates pending persistence, and restores owner state; other-user read-only presentation remains incomplete. |
+| `SVC-MOVE-001` | `STATICALLY_ALIGNED` | Direct routes now wait for topology and enforce host count, stack `reassign_allowed`, installed component, and available target without inventing an API. |
+| `SVC-MOVE-002` | `UNCHANGED_PARTIAL` | Review content and downtime/recommendation completeness remain runtime-required. |
+| `SVC-MOVE-003` | `IMPROVED_PARTIAL` | DB task IDs are passed in the correct order and pending polling is awaited; full mutation idempotency and partial-failure recovery remain incomplete. |
+| `SVC-MOVE-004` | `STATICALLY_ALIGNED` | Manual-step eligibility is shared across wizard construction and Step 4 task filtering; Oozie current config distinguishes Derby from external databases, load failure is retryable, and Oozie/MySQL commands are component-specific. |
+| `SVC-MOVE-005` | `IMPROVED_PARTIAL` | DB task polling now settles correctly; affected-service checks and complete task retry/summaries remain partial. |
+| `SVC-MOVE-006` | `STATICALLY_ALIGNED` | A failed DB test exposes the classic narrow rollback sequence; target deletion is idempotent for 404/`NoSuchResourceException` retries. |
+
+## Feature Status
+
+### Service Navigation, Global Actions, and Single-Service Actions
+
+| ID | Initial status | React evidence and gap |
+| --- | --- | --- |
+| `SVC-NAV-001` | `PARTIAL` | The Services sidebar and Summary navigation exist, but service-event convergence, invalid-service fallback, state/restart/alert fidelity, and recovery require completion and runtime validation. |
+| `SVC-ALL-001` | `PARTIAL` | A seven-step Add Service wizard exists. The menu and route omit `supports.enableAddDeleteServices`, active-wizard ownership, upgrade, and route-authorization parity. |
+| `SVC-ALL-002` | `PARTIAL` | Start All correctly uses the broad cluster-wide service PUT used by classic, but omits the classic health-based disabled state, confirmation, request progress, and recoverable failure lifecycle. |
+| `SVC-ALL-003` | `PARTIAL` | Stop All correctly uses the broad cluster-wide service PUT used by classic, but omits the health-based disabled state, impact/HDFS checkpoint confirmation, request progress, and recoverable failure lifecycle. |
+| `SVC-ALL-004` | `PARTIAL` | Restart All and the stale-component request shape exist, but the confirmation/progress/recovery lifecycle and exact payload lacked focused evidence. Classic global behavior is one POST, not the rolling choice stated in the written baseline. |
+| `SVC-ALL-005` | `PARTIAL` | Cluster client-config download exists, but the legacy outer-menu permission quirk, popup-blocked behavior, and browser acceptance remain unverified. |
+| `SVC-ACT-001` | `PARTIAL` | Start, Stop, and Restart are present, but action eligibility, upgrade/wizard exclusion, rolling scheduling, and state recovery do not fully match classic. |
+| `SVC-ACT-002` | `PARTIAL` | Service Check is present, but permission gating, stack availability, result presentation, and failure/retry behavior are incomplete. |
+| `SVC-ACT-003` | `PARTIAL` | Service maintenance is present, but component/alert effects and state convergence need validation. |
+| `SVC-ACT-004` | `PARTIAL` | Restart-required component flows exist, but stale filtering, parameter selection, scheduling, and progress coverage are incomplete. |
+| `SVC-ACT-005` | `PARTIAL` | Delete Service exists, but the feature flag, stopped/dependency/last-service checks, wizard exclusion, and complete confirmation contract are not aligned. |
+| `SVC-ACT-006` | `PARTIAL` | YARN queue refresh exists but is exposed through overly broad authorization and needs command-availability and progress validation. |
+| `SVC-ACT-007` | `PARTIAL` | HDFS rebalance exists but is exposed through overly broad authorization; NameNode/DataNode eligibility, threshold validation, progress, and recovery are incomplete. |
+| `SVC-ACT-008` | `PARTIAL` | Some service-specific commands exist, but stack command coverage, state conditions, and semantic permission gates are incomplete. |
+| `SVC-ACT-009` | `PARTIAL` | Dynamic custom commands exist, but command metadata scopes, parameters, authorization, progress, and recovery require alignment. |
+| `SVC-ACT-010` | `PARTIAL` | HA, federation, JournalNode, standby, and move-master entries exist selectively; permissions are too broad and service/component/feature conditions remain incomplete. |
+| `SVC-ACT-011` | `PARTIAL` | Downloads exist, but current-service all-client download incorrectly uses `SERVICE_COMPONENT`; it must use `SERVICE`, reserving `SERVICE_COMPONENT` for a specified client component. |
+
+### Non-Metrics Summary and Quick Links
+
+| ID | Initial status | React evidence and gap |
+| --- | --- | --- |
+| `SVC-SUM-001` | `PARTIAL` | Summary renders service/component/state/alert information, but service-specific layouts, maintenance, restart-required, and host distribution parity are incomplete. |
+| `SVC-SUM-002` | `PARTIAL` | Host/component navigation exists in places, but return-path and Hosts-filter semantics cross the Module 03 ownership boundary and require integration after that module lands. |
+| `SVC-SUM-003` | `MISSING` | React has no complete individual host-component Start, Stop, Restart, Maintenance, or custom-command action set in Service Summary. |
+| `SVC-SUM-004` | `MISSING` | Flume agent Start/Stop by host and handler is absent. |
+| `SVC-SUM-005` | `PARTIAL` | External Quick Links are rendered, but descriptor/config/host resolution is incomplete and the separate Ambari View route/iframe behavior is not reconciled. |
+| `SVC-QL-001` | `PARTIAL` | Visible-link and empty/error handling exists, but descriptor loading has a malformed URL and removal/component-existence semantics need focused coverage. |
+| `SVC-QL-002` | `PARTIAL` | Protocol checks are partially implemented; exact `EXIST`, `NOT_EXIST`, fixed policy, reverse-protocol, and missing-property behavior need deterministic tests. |
+| `SVC-QL-003` | `PARTIAL` | Component hosts are loaded, but internal-to-public-host mapping and all single/multi-host/nameservice grouping cases are incomplete. |
+| `SVC-QL-004` | `PARTIAL` | Port/default resolution exists, but login substitution is always empty and `${config-type/property-name}` substitution is missing. |
+| `SVC-QL-005` | `PARTIAL` | Ranger handling is partial; MapReduce configured-host reverse/public-host resolution is incomplete and Oozie hosts are not restricted to `STARTED`. |
+| `SVC-QL-006` | `PARTIAL` | Active/Standby grouping is present in part, but HDFS/YARN/HBase operational selection and required non-display active-master field need validation. |
+| `SVC-QL-007` | `STATICALLY_ALIGNED` | External anchors use `_blank` with `noreferrer`; runtime validation must confirm every rendering branch and generated URL. |
+
+### Service Configs and Config Groups
+
+| ID | Initial status | React evidence and gap |
+| --- | --- | --- |
+| `SVC-CONFIG-001` | `PARTIAL` | Theme/category controls exist, but control types, missing-theme fallback, tabs/sections, and stack metadata coverage require executable validation. |
+| `SVC-CONFIG-002` | `PARTIAL` | Values, metadata, descriptions, units, and validation are rendered in part; recommended/default/final/read-only semantics are not fully covered. |
+| `SVC-CONFIG-003` | `PARTIAL` | Editing, validation, recommendations, dependencies, undo, and final flags exist unevenly across traditional rows and widgets; permission and error blocking require alignment. |
+| `SVC-CONFIG-004` | `INCORRECT` | Default-group saves include only changed properties even though desired-config replacement requires all properties for each changed type. Save promises are not awaited, so `saveInProgress`, success, refresh, and dependent-service failures race. |
+| `SVC-CONFIG-005` | `INCORRECT` | The unsaved-navigation prompt exists, but Save can fail to call `blocker.proceed()` when validation has no warnings, and refresh relies on a fixed one-second delay instead of save completion. |
+| `SVC-CONFIG-006` | `PARTIAL` | History, version selection, and comparison exist, but Compare lacks `SERVICE.COMPARE_CONFIGS`; old-version read-only and group/version selection need validation. |
+| `SVC-CONFIG-007` | `INCORRECT` | Make Current sends the required cluster PUT, but lacks `SERVICE.MODIFY_CONFIGS`; its follow-up current-version GET is malformed and uses a hard-coded service set instead of installed services. |
+| `SVC-CONFIG-008` | `PARTIAL` | Override controls exist, but empty override values are lost through truthy fallback and widget/row recommended/final/restore behavior needs coverage. |
+| `SVC-CONFIG-009` | `PARTIAL` | Restart-required actions exist but permission, maintenance/state filters, host/component grouping, rolling parameters, and progress are incomplete. |
+| `SVC-CONFIG-010` | `INCORRECT` | DB custom-action create, task-list, and polling failures can leave the widget in Connecting. KDC uses `finally`, but the DB path does not expose complete failure recovery. |
+| `SVC-CONFIG-011` | `PARTIAL` | Custom property controls exist, but category eligibility, bulk parsing, duplicate/key validation, persisted deletion, permission, and save integration need focused tests. |
+| `CFG-GROUP-001` | `PARTIAL` | Group listing exists, but management is gated by `SERVICE.MODIFY_CONFIGS` instead of `SERVICE.MANAGE_CONFIG_GROUPS`. |
+| `CFG-GROUP-002` | `PARTIAL` | Create/name/description/host selection exists; one-non-default-group-per-service enforcement and server failure recovery require alignment. |
+| `CFG-GROUP-003` | `PARTIAL` | Rename/description/copy UI exists, but duplicate does not copy desired configs and name uniqueness needs validation. Classic intentionally leaves the copied group's host list empty. |
+| `CFG-GROUP-004` | `PARTIAL` | Host add/remove exists, but the selection UI cannot move a host directly from another non-default group and route/current-group refresh is incomplete. |
+| `CFG-GROUP-005` | `PARTIAL` | Delete exists; default-group protection, host return-to-default, selection refresh, and recoverable failure need validation. |
+| `CFG-GROUP-006` | `PARTIAL` | Group properties and edit entry exist, but preselected group/version routing and historical selection need runtime validation. |
+
+### Add Service and Reassign Master
+
+| ID | Initial status | React evidence and gap |
+| --- | --- | --- |
+| `SVC-ADD-001` | `PARTIAL` | Service choice exists; installability, dependencies, conflicts, validation, feature flag, and mutual exclusion require alignment. |
+| `SVC-ADD-002` | `PARTIAL` | Master assignment exists; cardinality, resources, existing components, ineligible hosts, and recovery need validation. |
+| `SVC-ADD-003` | `PARTIAL` | Slave/client assignment exists; retained installed components and host eligibility need validation. |
+| `SVC-ADD-004` | `PARTIAL` | Config customization exists; recommendation, credential/database/account tabs, dependency handling, and failure recovery are incomplete. |
+| `SVC-ADD-005` | `PARTIAL` | Review exists; all component/config changes and no-mutation behavior need executable acceptance evidence. |
+| `SVC-ADD-006` | `PARTIAL` | Deploy executes installation stages, but exact request ordering/payloads, route lock, progress, retry, and partial-failure recovery require validation. |
+| `SVC-ADD-007` | `INCORRECT` | Completion always writes `Clusters.provisioning_state=INSTALLED`; Add Service must only refresh the existing cluster and close. |
+| `SVC-ADD-008` | `PARTIAL` | Step persistence exists, but another user's read-only mode, mutual exclusion, close cleanup, and correct Add Service context ownership are incomplete. |
+| `SVC-MOVE-001` | `INCORRECT` | `ValidateMove` hard-codes `canStartMove=true` and direct routes bypass classic's host-count, stack reassignability, installed-component, and available-target checks. Classic performs these checks from loaded topology; it does not call a separate validation API. |
+| `SVC-MOVE-002` | `PARTIAL` | Review exists, but source/target, affected config/service, recommendation, and downtime-warning completeness need validation. |
+| `SVC-MOVE-003` | `PARTIAL` | Configure Component contains extensive mutation logic; exact ordering, payloads, idempotency, and partial-failure recovery need executable validation. |
+| `SVC-MOVE-004` | `PARTIAL` | Conditional manual-command steps exist, but component-specific commands, confirmations, route persistence, and resume behavior need validation. |
+| `SVC-MOVE-005` | `PARTIAL` | Start/Test flows exist, but affected-service selection, service checks, task summaries, retry, and failure recovery are incomplete. |
+| `SVC-MOVE-006` | `MISSING` | React lacks classic's narrow rollback path for a failed database connection task. Classic step 7 removes the failed target component, reconfigures the database service, and restarts services; it is not a general restore of every component move. Module 04 implements this narrow compatibility path rather than inventing a general rollback contract. |
+
+## React File Inventory
+
+The primary Module 04 implementation surface is:
+
+- Service shell and actions: `screens/Services/ServiceLoader.tsx`, `ServiceDashboard.tsx`, `ServiceSummary.tsx`, `ServiceComponents.tsx`, `Actions.tsx`, `ServiceActionsUrlMapping.tsx`, and `ComponentActionsMapping.tsx`.
+- Quick Links: `screens/Services/ServiceQuicklinks.tsx`, `OptimizedServiceQuicklinks.tsx`, `hooks/useLazyQuicklinks.ts`, and `api/quicklinksApi.ts`.
+- Service Configs: `screens/ServiceConfigs/index.tsx`, `screens/CommonConfigs/*`, `screens/ConfigVersions/*`, `hooks/useConfigSaver.tsx`, `hooks/useConfigs.ts`, `hooks/useConfigsTags.ts`, `hooks/useEnhancedConfigs.ts`, `api/configsApi.ts`, and `api/serviceConfigApi.ts`.
+- Config Groups: `screens/ConfigGroups/*`, `Utils/configGroupUtils.ts`, and `api/configGroupApi.ts`.
+- Add Service: `screens/Services/AddServiceWizard/*`, `screens/Services/AddWizardUrlMapping.tsx`, and shared Cluster Wizard step components.
+- Reassign Master: `screens/Services/reassign/*`, move initializers, and `api/serviceApi.ts`.
+- Shared state, routes, permissions, and requests: `store/ServiceContext.tsx`, application routing, `api/servicesApi.ts`, `api/actionsApi.ts`, and permission utilities.
+
+Files under `screens/Hosts`, including `HostConfigs.tsx`, `actions.tsx`, `supportClientConfigsDownload.ts`, and Add Host wizard state, are owned by Module 03 and are not changed by Module 04.
+
+## Backend Contract Comparison
+
+| Ember contract | Initial React difference | Required Module 04 behavior |
+| --- | --- | --- |
+| `PUT /api/v1/clusters/{cluster}/services?{urlParams}` | React uses the same broad state mutation as classic, but lacks the surrounding confirmation and recovery lifecycle | Preserve the broad classic request with `ServiceInfo.state`, request context, optional operator query, progress tracking, and retry after rejection |
+| `PUT /api/v1/clusters/{cluster}/services/{service}` | State, maintenance, and request-context handling varies by action | Preserve exact desired-state or maintenance payload and response progress semantics |
+| `POST /api/v1/clusters/{cluster}/requests` | Custom commands and service checks share incomplete authorization/error paths | Preserve command name, resource filters, parameters, request context, and async task ownership |
+| `POST /api/v1/clusters/{cluster}/request_schedules` | Per-service immediate versus rolling/scheduled restart selection is incomplete | Preserve ordered batch requests, interval, task tolerance, and request-schedule response type for per-service Summary/Configs flows |
+| `PUT /api/v1/clusters/{cluster}` with `Clusters.desired_config` | Save emits only changed properties for default groups and does not await requests | Send all properties and attributes for every changed config type; await every current/dependent service save |
+| `GET /api/v1/clusters/{cluster}/configurations/service_config_versions` | History reads exist, but permission/selection/revert semantics are incomplete | Preserve service/group/version filters and treat old versions as immutable history |
+| Create a new desired config from a historical version | `setIsCurrent()` performs a malformed GET | Build and PUT a new desired config version with an audit note; never mutate the historical row |
+| Config group CRUD at `/api/v1/clusters/{cluster}/config_groups` | CRUD URLs are broadly correct; duplicate desired configs and cross-group host movement are incomplete | Copy desired configs but leave duplicate hosts empty, clear hosts from their previous non-default group before assigning the target group, and refresh selection |
+| `GET /api/v1/stacks/{stack}/versions/{version}/services/{service}/quicklinks` | `QuicklinksApi.getQuicklinks()` appends a stray apostrophe | Use the exact descriptor URL and preserve descriptor-empty error handling |
+| `GET /api/v1/clusters/{cluster}/hosts?Hosts/host_name.in({hosts})&fields=Hosts/public_host_name{urlParams}&minimal_response=true` | Public-host mapping request is absent | Map internal component hosts to public host names before generating external URLs |
+| Grouped multi-version configuration predicate containing `%26` | React URL construction must be verified | Encode the grouped `&` as `%26`, matching Ambari predicate parsing |
+| `GET .../services/{service}/components?...` | `getAllServiceComponentsListAndInitialMetrics()` has a trailing backtick | Remove malformed URL text; Module 04 uses only non-Metrics fields |
+| `POST /api/v1/clusters/{cluster}/services?ServiceInfo/service_name={service}` | `createComponent()` has the correct collection URL and body but omits `method`, so it can default to GET | Send POST with the component body used by classic `common.create_component` |
+| `GET /api/v1/clusters/{cluster}?fields=Clusters/desired_configs...` | `ConfigsApi.getDesiredConfigsInfo()` has a trailing backtick | Use the exact desired-config query URL |
+| `GET ...?format=client_config_tar` with `HostRoles/component_name={scope}` | Current-service all-client download uses component scope | Use `CLUSTER` for all services, `SERVICE` for all clients of one service, and `SERVICE_COMPONENT` for one client component |
+
+The default-group save contract is replacement-oriented: once a config type is changed, its submitted `properties` object must contain every property in that type, including unchanged values. `properties_attributes` must preserve final and related attributes. Non-default config-group saves retain the classic parallel, non-atomic server behavior, but the React lifecycle must await all started promises and report every failure deterministically.
+
+### Implemented Request Corrections
+
+| Flow | Method and exact resource | Request/query/payload correction |
+| --- | --- | --- |
+| Compare two versions | `GET /api/v1/clusters/{cluster}/configurations/service_config_versions?(service_name={service}%26service_config_version.in({v1},{v2}))` | Encodes the grouped predicate separator as `%26` instead of sending a raw `&`. |
+| Quick Link descriptor | `GET /api/v1/stacks/{stack}/versions/{version}/services/{service}/quicklinks?QuickLinkInfo/default=true&fields=*&_={timestamp}` | Removes the trailing apostrophe that changed the descriptor resource. |
+| Quick Link public hosts | `GET /api/v1/clusters/{cluster}/hosts?Hosts/host_name.in({encodedHosts})&fields=Hosts/public_host_name&minimal_response=true` | URL-encodes each hostname and maps `Hosts.host_name` to `Hosts.public_host_name`. |
+| Component topology | `GET /api/v1/clusters/{cluster}/components?fields={nonMetricsFields}&_={timestamp}` | Removes the trailing backtick and uses only service/component, hostname, and state fields for this module. |
+| Create service component | `POST /api/v1/clusters/{cluster}/services?ServiceInfo/service_name={service}` | Adds the missing POST method and sends `components[].ServiceComponentInfo.component_name`. |
+| Desired config refresh | `GET /api/v1/clusters/{cluster}?fields=Clusters/desired_configs&_={timestamp}` | Removes the trailing backtick. |
+| Default config save | `PUT /api/v1/clusters/{cluster}` | Sends `Clusters.desired_config[]` with the complete `properties` replacement and every non-empty `properties_attributes` category for each changed type. |
+| Make Current | `PUT /api/v1/clusters/{cluster}` followed by current-version GET | Sends `Clusters.desired_service_config_versions` with service, selected version, and note; refreshes the actual installed-service list through a corrected current-version URL. |
+| Config Group membership | `PUT /api/v1/clusters/{cluster}/config_groups/{id}` | Phase 1 sends `ConfigGroup.hosts: []` for every membership-changed/deleted group; phase 2 writes final memberships before creates, preventing cross-group swap conflicts. |
+| Config Group delete | `PUT .../config_groups/{id}` then `DELETE .../config_groups/{id}` | Clears hosts before DELETE so they return to Default and the operation remains retryable after a failed stage. |
+| Start/Stop All | `PUT /api/v1/clusters/{cluster}/services?` | Preserves classic's broad resource with `RequestInfo.context`, cluster operation level, and `Body.ServiceInfo.state` (`STARTED` or `INSTALLED`). |
+| Restart All Required | `POST /api/v1/clusters/{cluster}/requests` | Sends one Classic-compatible request with `RequestInfo.command=RESTART`, context `Restart all required services`, operation level `host_component`, and `Requests/resource_filters[0].hosts_predicate=HostRoles/stale_configs=true&HostRoles/cluster_name={cluster}`. |
+| Service maintenance | `PUT /api/v1/clusters/{cluster}/services/{service}` | Sends `RequestInfo.context` and `Body.ServiceInfo.maintenance_state` (`ON` or `OFF`), then converges local state only after success. |
+| Flume agent state | `PUT /api/v1/clusters/{cluster}/hosts/{host}/host_components/FLUME_HANDLER` | Sends `RequestInfo.flume_handler={agent}`, a `HOST_COMPONENT` operation level for FLUME and the target host, and `Body.HostRoles.state` (`STARTED` or `INSTALLED`). |
+| Test Connection | `POST /api/v1/clusters/{cluster}/requests` or the uninstalled-service custom-action resource | Preserves `RequestInfo.parameters` and `Requests/resource_filters[].hosts`; task-list and task-detail IDs are awaited and non-zero `structured_out.db_connection_check.exit_code` is failure. |
+| Oozie manual-step eligibility | `GET /api/v1/clusters/{cluster}/configurations/service_config_versions?service_name.in(OOZIE)&is_current=true&fields=*` | Reads the current `oozie-site/oozie.service.JPAService.jdbc.driver`; only Derby uses the embedded-database manual copy steps, while load failure blocks entry and exposes Retry. |
+| Reassign DB rollback | Host-component maintenance PUT, target component DELETE, MySQL clean/configure commands, then service start | Uses the persisted source/target and affected component list; no separate validation or universal rollback API is introduced. |
+| Client download scope | Browser GET ending in `?format=client_config_tar` | Uses `CLUSTER` for all cluster clients, `SERVICE` for one service's clients, and `SERVICE_COMPONENT` only for one named client component. |
+
+## Permissions, Feature Flags, and Routes
+
+| Entry or operation | Required semantic gate | Initial React difference |
+| --- | --- | --- |
+| Service Configs tab | `CLUSTER.VIEW_CONFIGS` and a configurable service | React additionally hides Configs during upgrades; classic does not |
+| Add/Delete Service | `SERVICE.ADD_DELETE_SERVICES` and `supports.enableAddDeleteServices` | Feature flag, route guard, and complete wizard/upgrade ownership checks are missing |
+| Start/Stop/Restart | `SERVICE.START_STOP` plus state, maintenance, upgrade, and wizard conditions | The broad action menu gate does not enforce every per-action condition |
+| Service Check | `SERVICE.RUN_SERVICE_CHECK` | Current authorization is too broad |
+| Custom command | `SERVICE.RUN_CUSTOM_COMMAND` | Current authorization is too broad for metadata-driven commands |
+| Maintenance | `SERVICE.TOGGLE_MAINTENANCE` | State and affected-component/alert convergence are incomplete |
+| HA/Federation | `SERVICE.ENABLE_HA` plus stack/service/component conditions | Entries use incomplete semantic permissions and availability conditions |
+| Move master | `SERVICE.MOVE` plus component conditions | Route and validator must reject unauthorized or invalid direct navigation |
+| Manage JournalNodes | Its classic semantic permission and feature/service conditions | Current entry inherits a broader action permission |
+| Compare Configs | `SERVICE.COMPARE_CONFIGS` | Gate is missing |
+| Modify/Make Current | `SERVICE.MODIFY_CONFIGS` | Make Current gate is missing; management currently conflates this with config groups |
+| Manage Config Groups | `SERVICE.MANAGE_CONFIG_GROUPS` | React uses `SERVICE.MODIFY_CONFIGS` |
+| Client config download | `CLUSTER.VIEW_CONFIGS`, scope-specific availability, and the legacy outer-menu gate | Scope and some menu conditions differ |
+
+Direct route entry must enforce the same permissions, feature flags, service/component availability, wizard ownership, and upgrade conditions as its menu item. Hiding a menu entry alone is not authorization parity. The classic placeholder Audit route is not a React acceptance requirement.
+
+### Implemented Permission And Route Results
+
+| Area | Final React result | Remaining acceptance |
+| --- | --- | --- |
+| Configs tab | Requires `CLUSTER.VIEW_CONFIGS` and remains visible during upgrades. | Verify each configurable/non-configurable service live. |
+| Add/Delete Service | Requires `SERVICE.ADD_DELETE_SERVICES`, `enableAddDeleteServices`, and no conflicting wizard/upgrade; Add Service direct routes apply all three gates. | Other-user read-only presentation and full wizard recovery remain partial. |
+| Service Check | Requires `SERVICE.RUN_SERVICE_CHECK`. | Stack support and result/retry UI remain partial. |
+| HDFS/YARN/custom commands | Require `SERVICE.RUN_CUSTOM_COMMAND`. | Exhaustive stack metadata and state predicates remain partial. |
+| Restart entries | Require `SERVICE.START_STOP`. | Rolling/scheduled parameter acceptance remains partial. |
+| Service maintenance | Requires `SERVICE.TOGGLE_MAINTENANCE`; success updates the selected service state and failure exposes Retry. | Component and alert convergence requires live acceptance. |
+| Flume handlers | Require `SERVICE.START_STOP`, valid handler state, and no active wizard owned by the current flow. | Verify server-side role rejection and realtime/poll convergence live. |
+| HA/Federation/Journal | Menu and direct routes require `SERVICE.ENABLE_HA` and the shared operation guard. | Every stack/service/component feature condition remains partial. |
+| Move master | Menu and direct routes require `SERVICE.MOVE`; topology validation rejects invalid direct entry. | Component-specific review/manual-step coverage remains partial. |
+| Compare/Make Current | Require `SERVICE.COMPARE_CONFIGS` and `SERVICE.MODIFY_CONFIGS`, respectively. | Non-default historical selection requires live acceptance. |
+| Config Groups | Requires `SERVICE.MANAGE_CONFIG_GROUPS`. | 403/409/500 server responses require live acceptance. |
+
+## Async Lifecycle, Recovery, and Persistence
+
+| Flow | Initial defect | Required convergence and recovery |
+| --- | --- | --- |
+| Service mutations | Batch filters and confirmation/retry are incomplete | Lock duplicate submission, show progress for real request IDs, refresh service/component state after success, and expose retry after failure |
+| Service/config realtime | App-level `/events/configs` subscription exists but Service Configs and Quick Links do not consume it | Refresh or invalidate relevant current configs and generated links without parallel polling or stale overwrite |
+| Default config save | Save promises are launched but not returned/awaited | Keep saving state until every request settles; refresh cluster/configs/Quick Links only after success; retain edits and expose errors after failure |
+| Dependent/non-default save | Parallel server operations can partially succeed | Report per-service failures deterministically, refresh confirmed successes, and never announce full success before all promises settle |
+| Unsaved route blocker | Save can leave navigation blocked; refresh waits a fixed one second | Proceed only after a successful awaited save; Discard proceeds immediately; Cancel keeps the user and edits; failed save remains blocked and recoverable |
+| Test Connection | Create/task/poll rejection can remain Connecting | End Connecting for create, task-list, and poll errors; display recoverable failure details; cancel timers and stale updates on unmount/retry |
+| Quick Links | Manual refresh and stale configs can leave old URLs | Handle load errors explicitly, allow Retry, refresh on current-config change/event, and never construct a URL without a valid descriptor/host |
+| Add Service | Step persistence exists, but ownership/cleanup differs | Restore persisted step for the owner; other users remain read-only; close invokes Add Service cleanup; completion refreshes services without changing provisioning state |
+| Reassign Master | Persistence exists, validation/rollback do not | Persist source/target and step, validate before mutations, resume deterministically, stop on failures, and offer component-specific rollback |
+
+### Implemented Lifecycle Results
+
+| Flow | Final behavior | Evidence or residual risk |
+| --- | --- | --- |
+| Default config save | Owns and awaits the replacement PUT, holds busy state through settlement, refreshes only after success, and returns failure without navigating. | Focused hook tests cover pending and rejected requests; dependent multi-service partial success still needs live acceptance. |
+| Unsaved navigation | Save proceeds only after successful settlement; failed Save remains blocked, while existing Discard/Cancel semantics remain available. | TypeScript and focused save tests pass; browser Back/Forward remains live-only. |
+| Test Connection | Create, task-list, poll, missing status/IDs, terminal failure, and non-zero DB check exit all stop polling and enable Retry. | Focused component tests cover create rejection, poll rejection, and completed-task DB failure. |
+| Quick Links | Correctly resolves user/config placeholders, component/public hosts, MapReduce host overrides, and Oozie running hosts; topology-read failure falls back to legacy single-link reconstruction. | Helper/API tests pass; live descriptor and config-event refresh remain. |
+| Config Groups | Local moves are atomic; server saves clear all changed memberships before set/create; errors remain visible and Save is retryable. | Pure planning/state tests cover swaps, empty membership, moves, and delete-to-Default. |
+| Add Service | Cancel invalidates sequence/debounce in the Add Service provider; completion clears persisted state without changing cluster provisioning state. | Static/build evidence passes; reload, second-user, and partial deploy remain live-only. |
+| Reassign | Entry waits for App and service topology, validates classic predicates, awaits DB polling, and exposes the narrow rollback with idempotent target deletion. | Validation/rollback helpers are tested; live multi-stage failure and resume remain. |
+| Service navigation | Route params are the source of truth; Back/Forward, invalid services, unsupported tabs, and unauthorized Configs tabs converge with replacement navigation, while embedded wizard dashboards retain their routes. | Pure navigation tests pass; service create/delete event convergence remains live-only. |
+| Flume handlers | State-valid commands lock per agent, use the returned request ID for progress, refresh topology on completion, and expose Retry after submission or terminal request failure. | Helper, component, and exact payload tests pass; live handler state convergence remains pending. |
+| Service maintenance | Success updates the local service state only after the PUT settles; rejection keeps the prior state and offers Retry with server details. | Exact payload evidence passes; service/component/alert realtime convergence remains live-only. |
+| Custom properties | Bulk parsing preserves value text after the first `=`, reports source line numbers, validates trimmed keys, permits re-adding removed keys, and excludes persisted deletions from full replacement payloads. | Parser and config-saver tests pass; exhaustive widget/category rendering remains live-only. |
+| Reassign manual steps | Oozie config loading owns its failure state and Retry; one eligibility decision controls both wizard steps and configure-task filtering. | Derby, external Oozie DB, MySQL, load failure, and task-filter helpers are covered; reload/resume remains live-only. |
+
+## Five Independent Audits
+
+| Pass | Independent entry | Initial findings | Implementation acceptance |
+| --- | --- | --- | --- |
+| 1. Features and state semantics | All 60 baseline IDs, classic controllers/templates/routes, and React components/hooks | Similar page names conceal missing host-component actions, Flume actions, rollback, Start/Stop All confirmation and recovery, full config replacement, public-host links, and wizard ownership | Every ID has an explicit post-implementation status and focused evidence or a documented boundary |
+| 2. Backend APIs and payloads | AJAX definitions/calls, direct HTTP, browser entries, API classes, and mutation call sites | Stray URL characters, missing POST, wrong download scope, malformed Make Current, incomplete save properties, and missing public-host mapping | URL/method/query/payload tests assert exact requests and failure propagation |
+| 3. Permissions, feature flags, and routes | Classic permission/flag docs, route guards, menus, and direct React routes | Configs is wrongly upgrade-hidden; Add/Delete flags and direct-route guards are incomplete; Compare, Make Current, Config Groups, checks, commands, and wizards use incorrect gates | Role/flag/upgrade/wizard matrices cover both visible entry and direct navigation |
+| 4. Async lifecycle, polling, recovery, and persistence | Promise ownership, timers, realtime, blockers, wizard stores, and partial failures | Saves are not awaited, Test Connection can remain Connecting, config events do not converge consumers, Add Service cleanup is misowned, and Reassign lacks rollback | Focused tests cover rejection, retry, unmount, partial success, navigation continuation, and persisted resume |
+| 5. Tests and executable acceptance evidence | Existing test inventory, Vitest configuration, build, lint, and runtime scenarios | The base has no focused Module 04 Vitest suite; static reading cannot validate live Server behavior | Focused Vitest, full Vitest, TypeScript/Vite build, ESLint, `git diff --check`, and the runtime matrix are all recorded honestly |
+
+## Compatibility Decisions
+
+| Classic behavior or defect | React decision |
+| --- | --- |
+| Configs remains visible during an upgrade when the user can view configs | Preserve classic visibility; only mutations are disabled by their own upgrade/wizard conditions |
+| A default desired-config PUT replaces a config type | Always send the complete property set and attributes for each changed type, even when only one value changed |
+| Classic non-default/dependent saves are parallel and non-atomic | Do not claim atomicity; await every request and surface partial failures without clearing unsaved state prematurely |
+| Empty string is a valid override | Use nullish/explicit override selection, never truthy fallback |
+| Making a historical version current creates history | Create a new desired config version; never mutate or relabel the selected historical record |
+| Browser client-config and Quick Link navigation bypasses application HTTP handling | Keep direct browser navigation and secure external anchors; avoid inventing in-app retry for a browser download whose response cannot be observed |
+| Classic Quick Links substitutes public hosts and descriptor placeholders | Preserve the stack-driven algorithm rather than hard-coding service URLs |
+| Classic Quick Links can consume the HBase active-master field | Retain only the operational field needed for safe link selection; do not add Metrics display or analysis |
+| A missing Quick Link descriptor protocol policy falls back to `hdfs-site/dfs.http.policy`, including services such as HBase | Preserve the shared Classic fallback; do not force HTTP from a service-name capability table |
+| The written baseline assigns global rolling/scheduled behavior to Restart All Required | Follow executable Classic behavior: send one confirmed `restart.staleConfigs` POST globally; retain rolling/scheduled choices only on per-service Summary/Configs actions |
+| The all-services menu opens only for `SERVICE.START_STOP` or `SERVICE.ADD_DELETE_SERVICES`, even though Download and Run All Service Check have their own inner permissions | Preserve the outer-menu quirk for compatibility; the inner entries retain `CLUSTER.VIEW_CONFIGS` and `SERVICE.RUN_SERVICE_CHECK` respectively |
+| Add Service completion does not set cluster provisioning state | Remove the Installer-only mutation from Add Service completion |
+| Classic Add Service deploy route cannot be left through normal wizard navigation | Preserve route ownership and persisted recovery while still allowing deliberate cleanup on completion/cancel |
+| Classic Reassign validates component-specific placement and has a narrow DB-test rollback | Do not enable mutation until topology validation passes; after DB-test failure only, remove target components, reconfigure the database service, and restart affected services. |
+| Oozie Reassign shows embedded database copy commands only for Derby | Read current Oozie config before building the wizard; external databases omit those steps and a failed config read blocks entry with Retry |
+| A malformed classic response can leave some polling views busy | React must terminate busy state and provide retry for every create/read/poll failure |
+
+## Cross-Module Boundaries
+
+Module 04 currently imports Module 03-owned helpers from `screens/Hosts` for host-component actions, client-config download, and Reassign Step 5. This branch does not modify those files. The following integration work must wait for or be reconciled with Module 03:
+
+- `SVC-SUM-002`: exact Hosts filter, target route, and return-path behavior.
+- `SVC-SUM-003`: shared host-component action eligibility and payload helpers if Module 03 changes their contract.
+- `SVC-ACT-011`: shared browser download helper changes, if any, must be integrated after Module 03 rather than edited concurrently.
+- Reassign Step 5: any required changes to imported Hosts action utilities remain a boundary; Module 04 can adapt its own caller only.
+- `AddWizardUrlMapping.tsx` currently mixes Add Service and Add Host cleanup contexts. Module 04 may isolate Add Service ownership without changing Add Host state or behavior; any shared restructuring requires later integration.
+
+No Module 04 implementation may depend on uncommitted Module 03 behavior. Boundaries remain `CROSS_MODULE_BOUNDARY` until integrated and accepted.
+
+## Runtime Acceptance Matrix
+
+Static and unit evidence is insufficient to mark these features covered. At minimum, execute these scenarios against representative Ambari Server stacks:
+
+| Area | Automated status | Live Ambari Server status |
+| --- | --- | --- |
+| Exact API URL/method/payload corrections | Covered by focused Vitest for corrected API helpers and config replacement payloads | `PENDING` |
+| Permissions, feature flag, and operation route guard | Covered by policy and route-guard Vitest plus static route review | `PENDING` |
+| Config save and Test Connection recovery | Covered by focused hook/component Vitest | `PENDING` |
+| Quick Link substitution and host mapping | Covered by focused helper/API Vitest | `PENDING` |
+| Navigation, protocol policy, custom properties, and config-history selection | Covered by focused pure-function and config-saver Vitest | `PENDING` |
+| Global stale restart, service maintenance, and Flume handlers | Covered by exact payload plus Flume helper/component Vitest | `PENDING` |
+| Config Group ordering and local membership persistence | Covered by focused pure-function Vitest | `PENDING` |
+| Add Service and Reassign multi-stage workflows | Static TypeScript/build coverage plus focused persistence/validation tests | `PENDING` |
+| Hosts-owned integration scenarios | Not implemented in this branch by ownership rule | `BLOCKED_ON_MODULE_03` |
+| Metrics | Excluded from Module 04 | `NOT_APPLICABLE` |
+
+1. Navigate installed services with healthy, maintenance, restart-required, alerting, missing, removed, and newly event-created service states; exercise Back/Forward and invalid service IDs.
+2. Run Start/Stop All with mixed health states; confirm classic-compatible button eligibility, broad PUT resources, impact/checkpoint confirmation, 202 progress, rejection, Retry, and event/REST convergence.
+3. Run global Restart All Required and verify its single stale-component POST; separately run per-service/component immediate and rolling/scheduled restart with mixed stale/state/maintenance hosts and validate interval, tolerance, ordering, and schedule IDs.
+4. Exercise every service action as Cluster User, service operator, cluster administrator, and Ambari administrator during normal, upgrade, and active-wizard states; try direct routes as well as menu entries.
+5. Delete a stopped eligible service and reject running, dependency-blocked, last-service, feature-disabled, unauthorized, and server-failed cases.
+6. Run YARN refresh, HDFS rebalance with valid/invalid thresholds, service checks, custom commands, maintenance, HA/Federation, JournalNode management, and move-master entries on supported and unsupported stacks.
+7. Download all cluster clients, all clients for one service, and one client component; inspect `CLUSTER`, `SERVICE`, and `SERVICE_COMPONENT` query scopes and popup-blocked behavior.
+8. Render non-Metrics summaries for every installed service, navigate component/host links, exercise Flume handler actions, and defer individual host-component action integration to Module 03.
+9. Load Quick Links with HTTP-only, HTTPS-only, existence, non-existence, exact-value, missing-property, default-port, regex-port, public-host, override-host, nameservice, Active/Standby, and empty/error descriptors.
+10. Validate Ranger external URL, MapReduce configured-host reverse mapping, Oozie STARTED filtering, login username, config placeholders, Retry, config-event refresh, external target, and `rel` attributes.
+11. Load themed and non-themed configs across all non-Metrics control types; edit ordinary, widget, recommended, dependent, final, password, directory, database, custom, and bulk custom properties with errors and warnings.
+12. Save one and multiple config types and dependent services; inspect complete properties/attributes, audit notes, versions, partial failures, retries, duplicate-submit locking, recommendation clearing, and config/Quick Link refresh timing.
+13. Trigger unsaved Save/Discard/Cancel through service, group, history, browser Back/Forward, and wizard-related navigation; cover successful save, validation warning/error, HTTP failure, retry, and refresh.
+14. Browse, compare, and make current default/non-default historical versions under every relevant permission; verify immutable history and the newly created current version.
+15. Create and remove empty-string and non-empty overrides; restore saved/default values; set recommended/final independently in traditional rows and widgets.
+16. Test Hive, Oozie, Ranger, and Kerberos connections through create failure, missing task ID, task-list failure, poll failure, server failure with stdout/stderr/check message, success, Retry, and unmount.
+17. Create, rename, describe, copy, move hosts between, delete, and edit default/non-default config groups; verify unique names, copied configs with an empty copied host list, host return to default, current route, 403/409/500, and Retry.
+18. Run all seven Add Service steps with dependencies/conflicts, partial deployment failures, Retry, refresh, close, resume after reload, a second user, upgrade, direct route, and feature-disabled state; verify provisioning state is never changed.
+19. Run Reassign for every supported component with valid/invalid target hosts, dependency conflicts, manual commands, reload/resume, request failures, checks, and component-specific rollback.
+20. Leave and re-enter Service Configs and Quick Links during slow requests, config events, service events, reconnect, Retry, logout, and unmount; verify no stale overwrite, duplicate mutation, timer, or subscription remains.
+
+## Verification Commands
+
+Final local evidence from `ambari-web/latest`:
+
+| Check | Result |
+| --- | --- |
+| Focused Vitest: `npx vitest run src/Utils/configGroupSavePlan.test.ts src/Utils/customConfigProperties.test.ts src/Utils/flumeAgents.test.ts src/Utils/quicklinks.test.ts src/Utils/reassignManualCommands.test.ts src/Utils/reassignValidation.test.ts src/Utils/serviceGlobalActions.test.ts src/Utils/serviceNavigation.test.ts src/Utils/servicesConfigsPolicy.test.ts src/Utils/sslProtocolUtils.test.ts src/api/servicesConfigsApi.test.ts src/components/ServiceOperationRouteGuard.test.tsx src/ho [...]
+| Full Vitest: `npm test` | `PASS`: 29 files, 113 tests |
+| TypeScript/Vite: `npm run build` | `PASS`; existing Sass deprecations, duplicate `ServiceLoader` cases, existing `eval` notices, and chunk-size warnings remain |
+| Full ESLint: `npx eslint . --format json` | `FAIL`: 5,776 errors and 455 warnings from repository-wide existing debt |
+| New Module 04 files ESLint | `PASS`: 26 source and test files, 0 findings |
+| ESLint findings mapped to lines added by this patch | `PASS`: 0 findings |
+| `git diff --check` | `PASS` |
+
+The build warnings and full-lint baseline are not caused by Module 04 and are not refactored in this branch. Live Ambari Server scenarios remain explicitly `PENDING`; automated evidence does not replace the runtime acceptance matrix. No JIRA issue, commit, push, or pull request has been created.
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@ambari.apache.org
For additional commands, e-mail: commits-help@ambari.apache.org