Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

UI – Add policy automation modal for running scripts #22436

Draft
wants to merge 17 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changes/22118-run-scripts-fe
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* Add ability to trigger script run on policy failure
9 changes: 8 additions & 1 deletion frontend/interfaces/policy.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import PropTypes from "prop-types";
import { SelectedPlatformString } from "interfaces/platform";
import { IScript } from "./script";

// Legacy PropTypes used on host interface
export default PropTypes.shape({
Expand Down Expand Up @@ -42,8 +43,8 @@ export interface IPolicy {
critical: boolean;
calendar_events_enabled: boolean;
install_software?: IPolicySoftwareToInstall;
run_script?: Pick<IScript, "id" | "name">;
}

export interface IPolicySoftwareToInstall {
name: string;
software_title_id: number;
Expand Down Expand Up @@ -90,6 +91,10 @@ export interface ILoadTeamPoliciesResponse {
policies?: IPolicyStats[];
}

export interface ILoadTeamPolicyResponse {
policy: IPolicyStats;
}

export interface IPolicyFormData {
description?: string | number | boolean | undefined;
resolution?: string | number | boolean | undefined;
Expand All @@ -102,6 +107,8 @@ export interface IPolicyFormData {
calendar_events_enabled?: boolean;
// undefined from GET/LIST when not set, null for PATCH to unset
software_title_id?: number | null;
// null for PATCH to unset - note asymmetry with GET/LIST - see IPolicy.run_script
script_id?: number | null;
}

export interface IPolicyNew {
Expand Down
175 changes: 133 additions & 42 deletions frontend/pages/policies/ManagePoliciesPage/ManagePoliciesPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import {
IPoliciesCountResponse,
IPolicy,
} from "interfaces/policy";
import { API_ALL_TEAMS_ID, ITeamConfig } from "interfaces/team";
import { API_ALL_TEAMS_ID, API_NO_TEAM_ID, ITeamConfig } from "interfaces/team";

import configAPI from "services/entities/config";
import globalPoliciesAPI, {
Expand Down Expand Up @@ -52,6 +52,8 @@ import CalendarEventsModal from "./components/CalendarEventsModal";
import { ICalendarEventsFormData } from "./components/CalendarEventsModal/CalendarEventsModal";
import InstallSoftwareModal from "./components/InstallSoftwareModal";
import { IInstallSoftwareFormData } from "./components/InstallSoftwareModal/InstallSoftwareModal";
import PolicyRunScriptModal from "./components/PolicyRunScriptModal";
import { IPolicyRunScriptFormData } from "./components/PolicyRunScriptModal/PolicyRunScriptModal";

interface IManagePoliciesPageProps {
router: InjectedRouter;
Expand All @@ -74,6 +76,13 @@ interface IManagePoliciesPageProps {
const DEFAULT_SORT_DIRECTION = "asc";
const DEFAULT_PAGE_SIZE = 20;
const DEFAULT_SORT_COLUMN = "name";
const [
DEFAULT_AUTOMATION_UPDATE_SUCCESS_MSG,
DEFAULT_AUTOMATION_UPDATE_ERR_MSG,
] = [
"Successfully updated policy automations.",
"Could not update policy automations. Please try again.",
];

const baseClass = "manage-policies-page";

Expand Down Expand Up @@ -127,23 +136,18 @@ const ManagePolicyPage = ({
},
});

// loading state used by various policy updates on this page
jacobshandling marked this conversation as resolved.
Show resolved Hide resolved
const [isUpdatingPolicies, setIsUpdatingPolicies] = useState(false);
const [isUpdatingCalendarEvents, setIsUpdatingCalendarEvents] = useState(
false
);
const [
isUpdatingPolicySoftwareInstall,
setIsUpdatingPolicySoftwareInstall,
] = useState(false);
const [isUpdatingOtherWorkflows, setIsUpdatingOtherWorkflows] = useState(
false
);

const [selectedPolicyIds, setSelectedPolicyIds] = useState<number[]>([]);
const [showAddPolicyModal, setShowAddPolicyModal] = useState(false);
const [showDeletePolicyModal, setShowDeletePolicyModal] = useState(false);
const [showInstallSoftwareModal, setShowInstallSoftwareModal] = useState(
false
);
const [showPolicyRunScriptModal, setShowPolicyRunScriptModal] = useState(
false
);
const [showCalendarEventsModal, setShowCalendarEventsModal] = useState(false);
const [showOtherWorkflowsModal, setShowOtherWorkflowsModal] = useState(false);
const [
Expand Down Expand Up @@ -472,6 +476,10 @@ const ManagePolicyPage = ({
setShowInstallSoftwareModal(!showInstallSoftwareModal);
};

const togglePolicyRunScriptModal = () => {
setShowPolicyRunScriptModal(!showPolicyRunScriptModal);
};

const toggleCalendarEventsModal = () => {
setShowCalendarEventsModal(!showCalendarEventsModal);
};
Expand All @@ -484,6 +492,9 @@ const ManagePolicyPage = ({
case "install_software":
toggleInstallSoftwareModal();
break;
case "run_script":
togglePolicyRunScriptModal();
break;
case "other_workflows":
toggleOtherWorkflowsModal();
break;
Expand All @@ -495,20 +506,17 @@ const ManagePolicyPage = ({
webhook_settings: Pick<IWebhookSettings, "failing_policies_webhook">;
integrations: IZendeskJiraIntegrations;
}) => {
setIsUpdatingOtherWorkflows(true);
setIsUpdatingPolicies(true);
try {
await (!isAllTeamsSelected
? teamsAPI.update(requestBody, teamIdForApi)
: configAPI.update(requestBody));
renderFlash("success", "Successfully updated policy automations.");
renderFlash("success", DEFAULT_AUTOMATION_UPDATE_SUCCESS_MSG);
} catch {
renderFlash(
"error",
"Could not update policy automations. Please try again."
);
renderFlash("error", DEFAULT_AUTOMATION_UPDATE_ERR_MSG);
} finally {
toggleOtherWorkflowsModal();
setIsUpdatingOtherWorkflows(false);
setIsUpdatingPolicies(false);
!isAllTeamsSelected ? refetchTeamConfig() : refetchConfig();
}
};
Expand All @@ -517,7 +525,7 @@ const ManagePolicyPage = ({
formData: IInstallSoftwareFormData
) => {
try {
setIsUpdatingPolicySoftwareInstall(true);
setIsUpdatingPolicies(true);
const changedPolicies = formData.filter((formPolicy) => {
const prevPolicyState = policiesAvailableToAutomate.find(
(policy) => policy.id === formPolicy.id
Expand Down Expand Up @@ -548,7 +556,7 @@ const ManagePolicyPage = ({
responses.concat(
changedPolicies.map((changedPolicy) => {
return teamPoliciesAPI.update(changedPolicy.id, {
// "software_title_id:" 0 will unset software install for the policy
// "software_title_id": 0 will unset software install for the policy
// "software_title_id": X will set the value to the given integer (except 0).
software_title_id: changedPolicy.swIdToInstall || 0,
team_id: teamIdForApi,
Expand All @@ -558,20 +566,70 @@ const ManagePolicyPage = ({
await Promise.all(responses);
await wait(100); // prevent race
refetchTeamPolicies();
renderFlash("success", "Successfully updated policy automations.");
renderFlash("success", DEFAULT_AUTOMATION_UPDATE_SUCCESS_MSG);
} catch {
renderFlash(
"error",
"Could not update policy automations. Please try again."
);
renderFlash("error", DEFAULT_AUTOMATION_UPDATE_ERR_MSG);
} finally {
toggleInstallSoftwareModal();
setIsUpdatingPolicySoftwareInstall(false);
setIsUpdatingPolicies(false);
}
};

const onUpdatePolicyRunScript = async (
formData: IPolicyRunScriptFormData
) => {
try {
setIsUpdatingPolicies(true);
const changedPolicies = formData.filter((formPolicy) => {
const prevPolicyState = policiesAvailableToAutomate.find(
(policy) => policy.id === formPolicy.id
);

const turnedOff =
prevPolicyState?.run_script !== undefined &&
formPolicy.runScriptEnabled === false;

const turnedOn =
prevPolicyState?.run_script === undefined &&
formPolicy.runScriptEnabled === true;

const updatedRunScriptId =
prevPolicyState?.run_script?.id !== undefined &&
formPolicy.scriptIdToRun !== prevPolicyState?.run_script?.id;

return turnedOff || turnedOn || updatedRunScriptId;
});
if (!changedPolicies.length) {
renderFlash("success", "No changes detected.");
return;
}
const responses: Promise<
ReturnType<typeof teamPoliciesAPI.update>
>[] = [];
responses.concat(
changedPolicies.map((changedPolicy) => {
return teamPoliciesAPI.update(changedPolicy.id, {
// "script_id": 0 will unset running a script for the policy (a script never has ID 0)
// "script_id": X will sets script X to run when the policy fails
script_id: changedPolicy.scriptIdToRun || 0,
team_id: teamIdForApi,
});
})
);
await Promise.all(responses);
await wait(100);
refetchTeamPolicies();
jacobshandling marked this conversation as resolved.
Show resolved Hide resolved
renderFlash("success", DEFAULT_AUTOMATION_UPDATE_SUCCESS_MSG);
} catch {
renderFlash("error", DEFAULT_AUTOMATION_UPDATE_ERR_MSG);
} finally {
togglePolicyRunScriptModal();
setIsUpdatingPolicies(false);
}
};

const onUpdateCalendarEvents = async (formData: ICalendarEventsFormData) => {
setIsUpdatingCalendarEvents(true);
setIsUpdatingPolicies(true);

try {
// update team config if either field has been changed
Expand Down Expand Up @@ -624,15 +682,12 @@ const ManagePolicyPage = ({
await refetchTeamPolicies();
await refetchTeamConfig();

renderFlash("success", "Successfully updated policy automations.");
renderFlash("success", DEFAULT_AUTOMATION_UPDATE_SUCCESS_MSG);
} catch {
renderFlash(
"error",
"Could not update policy automations. Please try again."
);
renderFlash("error", DEFAULT_AUTOMATION_UPDATE_ERR_MSG);
} finally {
toggleCalendarEventsModal();
setIsUpdatingCalendarEvents(false);
setIsUpdatingPolicies(false);
}
};

Expand Down Expand Up @@ -802,9 +857,11 @@ const ManagePolicyPage = ({
const getAutomationsDropdownOptions = (configPresent: boolean) => {
let disabledInstallTooltipContent: React.ReactNode;
let disabledCalendarTooltipContent: React.ReactNode;
let disabledRunScriptTooltipContent: React.ReactNode;
if (!isPremiumTier) {
disabledInstallTooltipContent = "Available in Fleet Premium.";
disabledCalendarTooltipContent = "Available in Fleet Premium.";
disabledRunScriptTooltipContent = "Available in Fleet Premium.";
} else if (isAllTeamsSelected) {
disabledInstallTooltipContent = (
<>
Expand All @@ -820,6 +877,13 @@ const ManagePolicyPage = ({
calendar events.
</>
);
disabledRunScriptTooltipContent = (
<>
Select a team to manage
<br />
run script automation.
</>
);
}
const installSWOption = {
label: "Install software",
Expand All @@ -828,8 +892,16 @@ const ManagePolicyPage = ({
helpText: "Install software to resolve failing policies.",
tooltipContent: disabledInstallTooltipContent,
};
const runScriptOption = {
label: "Run script",
value: "run_script",
disabled: !!disabledRunScriptTooltipContent,
helpText: "Run script to resolve failing policies.",
tooltipContent: disabledRunScriptTooltipContent,
};

if (!configPresent) {
return [installSWOption];
return [installSWOption, runScriptOption];
}

return [
Expand All @@ -841,6 +913,7 @@ const ManagePolicyPage = ({
tooltipContent: disabledCalendarTooltipContent,
},
installSWOption,
runScriptOption,
{
label: "Other workflows",
value: "other_workflows",
Expand All @@ -858,6 +931,18 @@ const ManagePolicyPage = ({
if (!isRouteOk) {
return <Spinner />;
}

let teamsDropdownHelpText: string;
if (teamIdForApi === API_NO_TEAM_ID) {
teamsDropdownHelpText =
"Detect device health issues for hosts that are not on a team.";
jacobshandling marked this conversation as resolved.
Show resolved Hide resolved
} else if (teamIdForApi === API_ALL_TEAMS_ID) {
teamsDropdownHelpText = "Detect device health issues for all hosts.";
} else {
// a team is selected
teamsDropdownHelpText =
"Detect device health issues for all hosts assigned to this team.";
}
return (
<MainContent className={baseClass}>
<div className={`${baseClass}__wrapper`}>
Expand Down Expand Up @@ -910,19 +995,15 @@ const ManagePolicyPage = ({
)}
</div>
<div className={`${baseClass}__description`}>
<p>
{isAnyTeamSelected
? "Detect device health issues for all hosts assigned to this team."
: "Detect device health issues for all hosts."}
</p>
<p>{teamsDropdownHelpText}</p>
</div>
{renderMainTable()}
{config && automationsConfig && showOtherWorkflowsModal && (
<OtherWorkflowsModal
automationsConfig={automationsConfig}
availableIntegrations={config.integrations}
availablePolicies={policiesAvailableToAutomate}
isUpdating={isUpdatingOtherWorkflows}
isUpdating={isUpdatingPolicies}
onExit={toggleOtherWorkflowsModal}
onSubmit={onUpdateOtherWorkflows}
/>
Expand All @@ -947,7 +1028,17 @@ const ManagePolicyPage = ({
<InstallSoftwareModal
onExit={toggleInstallSoftwareModal}
onSubmit={onUpdatePolicySoftwareInstall}
isUpdating={isUpdatingPolicySoftwareInstall}
isUpdating={isUpdatingPolicies}
policies={policiesAvailableToAutomate}
// currentTeamId will at this point be present
teamId={currentTeamId ?? 0}
/>
)}
{showPolicyRunScriptModal && (
<PolicyRunScriptModal
onExit={togglePolicyRunScriptModal}
onSubmit={onUpdatePolicyRunScript}
isUpdating={isUpdatingPolicies}
policies={policiesAvailableToAutomate}
// currentTeamId will at this point be present
teamId={currentTeamId ?? 0}
Expand All @@ -964,7 +1055,7 @@ const ManagePolicyPage = ({
}
url={teamConfig?.integrations.google_calendar?.webhook_url || ""}
policies={policiesAvailableToAutomate}
isUpdating={isUpdatingCalendarEvents}
isUpdating={isUpdatingPolicies}
/>
)}
</div>
Expand Down
Loading
Loading