Skip to content

Commit

Permalink
Merge branch 'main' into feature/1968-topology-applications
Browse files Browse the repository at this point in the history
  • Loading branch information
Kiryous authored Sep 23, 2024
2 parents c41f345 + dda0ac7 commit 3f3138b
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 63 deletions.
60 changes: 29 additions & 31 deletions keep-ui/app/incidents/create-or-update-incident.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,14 @@ import { useIncidents } from "utils/hooks/useIncidents";

interface Props {
incidentToEdit: IncidentDto | null;
createCallback?: (id: string) => void
exitCallback?: () => void
createCallback?: (id: string) => void;
exitCallback?: () => void;
}

export default function CreateOrUpdateIncident({
incidentToEdit,
createCallback,
exitCallback
exitCallback,
}: Props) {
const { data: session } = useSession();
const { mutate } = useIncidents(true, 20);
Expand All @@ -34,12 +34,18 @@ export default function CreateOrUpdateIncident({
const editMode = incidentToEdit !== null;

// Display cancel btn if editing or we need to cancel for another reason (eg. going one step back in the modal etc.)
const cancellable = editMode || exitCallback
const cancellable = editMode || exitCallback;

useEffect(() => {
if (incidentToEdit) {
setIncidentName(incidentToEdit.user_generated_name ?? incidentToEdit.ai_generated_name ?? "");
setIncidentUserSummary(incidentToEdit.user_summary ?? incidentToEdit.generated_summary ?? "" );
setIncidentName(
incidentToEdit.user_generated_name ??
incidentToEdit.ai_generated_name ??
""
);
setIncidentUserSummary(
incidentToEdit.user_summary ?? incidentToEdit.generated_summary ?? ""
);
setIncidentAssignee(incidentToEdit.assignee ?? "");
}
}, [incidentToEdit]);
Expand Down Expand Up @@ -70,8 +76,8 @@ export default function CreateOrUpdateIncident({
await mutate();
toast.success("Incident created successfully");

const created = await response.json()
createCallback?.(created.id) // close the modal and associate the alert incident
const created = await response.json();
createCallback?.(created.id); // close the modal and associate the alert incident
} else {
toast.error(
"Failed to create incident, please contact us if this issue persists."
Expand All @@ -83,21 +89,18 @@ export default function CreateOrUpdateIncident({
const updateIncident = async (e: FormEvent) => {
e.preventDefault();
const apiUrl = getApiURL();
const response = await fetch(
`${apiUrl}/incidents/${incidentToEdit?.id}`,
{
method: "PUT",
headers: {
Authorization: `Bearer ${session?.accessToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
name: incidentName,
user_summary: incidentUserSummary,
assignee: incidentAssignee,
}),
}
);
const response = await fetch(`${apiUrl}/incidents/${incidentToEdit?.id}`, {
method: "PUT",
headers: {
Authorization: `Bearer ${session?.accessToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
user_generated_name: incidentName,
user_summary: incidentUserSummary,
assignee: incidentAssignee,
}),
});
if (response.ok) {
exitEditMode();
await mutate();
Expand All @@ -111,21 +114,16 @@ export default function CreateOrUpdateIncident({

// If the Incident is successfully updated or the user cancels the update we exit the editMode and set the editRule in the incident.tsx to null.
const exitEditMode = () => {
exitCallback?.()
exitCallback?.();
clearForm();
};

const submitEnabled = (): boolean => {
return (
!!incidentName
);
return !!incidentName;
};

return (
<form
className="py-2"
onSubmit={editMode ? updateIncident : addIncident}
>
<form className="py-2" onSubmit={editMode ? updateIncident : addIncident}>
<Subtitle>Incident Metadata</Subtitle>
<div className="mt-2.5">
<Text>
Expand Down
74 changes: 42 additions & 32 deletions keep/api/core/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -696,8 +696,9 @@ def get_workflow_executions(
).scalar()
avgDuration = avgDuration if avgDuration else 0.0

query = (query.order_by(desc(WorkflowExecution.started)).limit(limit).offset(offset)
)
query = (
query.order_by(desc(WorkflowExecution.started)).limit(limit).offset(offset)
)
# Execute the query
workflow_executions = query.all()

Expand Down Expand Up @@ -1750,6 +1751,7 @@ def update_key_last_used(
session.add(tenant_api_key_entry)
session.commit()


def get_linked_providers(tenant_id: str) -> List[Tuple[str, str, datetime]]:
with Session(engine) as session:
providers = (
Expand Down Expand Up @@ -2260,7 +2262,9 @@ def get_last_incidents(
return incidents, total_count


def get_incident_by_id(tenant_id: str, incident_id: str | UUID, with_alerts: bool = False) -> Optional[Incident]:
def get_incident_by_id(
tenant_id: str, incident_id: str | UUID, with_alerts: bool = False
) -> Optional[Incident]:
with Session(engine) as session:
query = session.query(
Incident,
Expand All @@ -2269,7 +2273,7 @@ def get_incident_by_id(tenant_id: str, incident_id: str | UUID, with_alerts: boo
Incident.id == incident_id,
)
if with_alerts:
query= query.options(joinedload(Incident.alerts))
query = query.options(joinedload(Incident.alerts))

return query.first()

Expand Down Expand Up @@ -2313,16 +2317,9 @@ def update_incident_from_dto_by_id(
if not incident:
return None

session.query(Incident).filter(
Incident.tenant_id == tenant_id,
Incident.id == incident_id,
).update(
{
"user_generated_name": updated_incident_dto.user_generated_name,
"user_summary": updated_incident_dto.user_summary,
"assignee": updated_incident_dto.assignee,
}
)
incident.user_generated_name = updated_incident_dto.user_generated_name
incident.user_summary = updated_incident_dto.user_summary
incident.assignee = updated_incident_dto.assignee

session.commit()
session.refresh(incident)
Expand Down Expand Up @@ -2374,7 +2371,10 @@ def get_incidents_count(


def get_incident_alerts_by_incident_id(
tenant_id: str, incident_id: str, limit: Optional[int] = None, offset: Optional[int] = None
tenant_id: str,
incident_id: str,
limit: Optional[int] = None,
offset: Optional[int] = None,
) -> (List[Alert], int):
with Session(engine) as session:
query = (
Expand Down Expand Up @@ -2458,8 +2458,10 @@ def inner(db_session: Session):
def add_alerts_to_incident_by_incident_id(
tenant_id: str, incident_id: str | UUID, alert_ids: List[UUID]
) -> Optional[Incident]:
logger.info(f"Adding alerts to incident {incident_id} in database, total {len(alert_ids)} alerts",
extra={"tags": {"tenant_id": tenant_id, "incident_id": incident_id}})
logger.info(
f"Adding alerts to incident {incident_id} in database, total {len(alert_ids)} alerts",
extra={"tags": {"tenant_id": tenant_id, "incident_id": incident_id}},
)

with Session(engine) as session:
query = select(Incident).where(
Expand All @@ -2482,27 +2484,39 @@ def add_alerts_to_incident_by_incident_id(
).all()
)

new_alert_ids = [alert_id for alert_id in alert_ids if alert_id not in existing_alert_ids]
new_alert_ids = [
alert_id for alert_id in alert_ids if alert_id not in existing_alert_ids
]

if not new_alert_ids:
return incident

alerts_data_for_incident = get_alerts_data_for_incident(new_alert_ids, session)

incident.sources = list(set(incident.sources) | set(alerts_data_for_incident["sources"]))
incident.affected_services = list(set(incident.affected_services) | set(alerts_data_for_incident["services"]))
incident.sources = list(
set(incident.sources) | set(alerts_data_for_incident["sources"])
)
incident.affected_services = list(
set(incident.affected_services) | set(alerts_data_for_incident["services"])
)
incident.alerts_count += alerts_data_for_incident["count"]

alert_to_incident_entries = [
AlertToIncident(alert_id=alert_id, incident_id=incident.id, tenant_id=tenant_id)
AlertToIncident(
alert_id=alert_id, incident_id=incident.id, tenant_id=tenant_id
)
for alert_id in new_alert_ids
]

for idx, entry in enumerate(alert_to_incident_entries):
session.add(entry)
if (idx + 1) % 100 == 0:
logger.info(f"Added {idx + 1}/{len(alert_to_incident_entries)} alerts to incident {incident.id} in database",
extra={"tags": {"tenant_id": tenant_id, "incident_id": incident.id}})
logger.info(
f"Added {idx + 1}/{len(alert_to_incident_entries)} alerts to incident {incident.id} in database",
extra={
"tags": {"tenant_id": tenant_id, "incident_id": incident.id}
},
)
session.commit()
session.flush()

Expand Down Expand Up @@ -2717,19 +2731,13 @@ def get_pmi_values_from_temp_file(temp_dir: str) -> Tuple[np.array, Dict[str, in

def get_tenant_config(tenant_id: str) -> dict:
with Session(engine) as session:
tenant_data = session.exec(
select(Tenant)
.where(Tenant.id == tenant_id)
).first()
tenant_data = session.exec(select(Tenant).where(Tenant.id == tenant_id)).first()
return tenant_data.configuration if tenant_data else {}


def write_tenant_config(tenant_id: str, config: dict) -> None:
with Session(engine) as session:
tenant_data = session.exec(
select(Tenant)
.where(Tenant.id == tenant_id)
).first()
tenant_data = session.exec(select(Tenant).where(Tenant.id == tenant_id)).first()
tenant_data.configuration = config
session.commit()
session.refresh(tenant_data)
Expand Down Expand Up @@ -2880,7 +2888,9 @@ def get_provider_by_name(tenant_id: str, provider_name: str) -> Provider:
return provider


def change_incident_status_by_id(tenant_id: str, incident_id: UUID | str, status: IncidentStatus) -> bool:
def change_incident_status_by_id(
tenant_id: str, incident_id: UUID | str, status: IncidentStatus
) -> bool:
with Session(engine) as session:
stmt = (
update(Incident)
Expand Down

0 comments on commit 3f3138b

Please sign in to comment.