From 1f4b4336333615a8a66ecbeef09fc3b839b4a18b Mon Sep 17 00:00:00 2001 From: Gidi Meir Morris Date: Thu, 11 Feb 2021 15:11:40 +0000 Subject: [PATCH] migrate alert to rule... doesnt work :( --- .../server/alerts_client/alerts_client.ts | 106 +++++++++--------- .../alerts/server/alerts_client_factory.ts | 2 +- .../alerts/server/health/get_health.ts | 16 +-- x-pack/plugins/alerts/server/health/task.ts | 2 +- x-pack/plugins/alerts/server/plugin.ts | 12 +- .../alerts/server/saved_objects/index.ts | 6 + .../alerts/server/saved_objects/migrations.ts | 26 ++++- .../saved_objects/partially_update_alert.ts | 2 +- .../task_runner/create_execution_handler.ts | 4 +- .../alerts/server/task_runner/task_runner.ts | 6 +- .../alerts/server/usage/alerts_telemetry.ts | 6 +- .../spaces_only/tests/alerting/index.ts | 2 +- .../spaces_only/tests/alerting/migrations.ts | 2 +- .../spaces_only/tests/index.ts | 2 +- 14 files changed, 112 insertions(+), 82 deletions(-) diff --git a/x-pack/plugins/alerts/server/alerts_client/alerts_client.ts b/x-pack/plugins/alerts/server/alerts_client/alerts_client.ts index 8ec7b36f595c73..c8cd0325acc9cf 100644 --- a/x-pack/plugins/alerts/server/alerts_client/alerts_client.ts +++ b/x-pack/plugins/alerts/server/alerts_client/alerts_client.ts @@ -240,7 +240,7 @@ export class AlertsClient { this.auditLogger?.log( alertAuditEvent({ action: AlertAuditAction.CREATE, - savedObject: { type: 'alert', id }, + savedObject: { type: 'rule', id }, error, }) ); @@ -292,14 +292,14 @@ export class AlertsClient { alertAuditEvent({ action: AlertAuditAction.CREATE, outcome: EventOutcome.UNKNOWN, - savedObject: { type: 'alert', id }, + savedObject: { type: 'rule', id }, }) ); let createdAlert: SavedObject; try { createdAlert = await this.unsecuredSavedObjectsClient.create( - 'alert', + 'rule', this.updateMeta(rawAlert), { ...options, @@ -327,7 +327,7 @@ export class AlertsClient { } catch (e) { // Cleanup data, something went wrong scheduling the task try { - await this.unsecuredSavedObjectsClient.delete('alert', createdAlert.id); + await this.unsecuredSavedObjectsClient.delete('rule', createdAlert.id); } catch (err) { // Skip the cleanup error and throw the task manager error to avoid confusion this.logger.error( @@ -336,7 +336,7 @@ export class AlertsClient { } throw e; } - await this.unsecuredSavedObjectsClient.update('alert', createdAlert.id, { + await this.unsecuredSavedObjectsClient.update('rule', createdAlert.id, { scheduledTaskId: scheduledTask.id, }); createdAlert.attributes.scheduledTaskId = scheduledTask.id; @@ -349,7 +349,7 @@ export class AlertsClient { }: { id: string; }): Promise> { - const result = await this.unsecuredSavedObjectsClient.get('alert', id); + const result = await this.unsecuredSavedObjectsClient.get('rule', id); try { await this.authorization.ensureAuthorized( result.attributes.alertTypeId, @@ -360,7 +360,7 @@ export class AlertsClient { this.auditLogger?.log( alertAuditEvent({ action: AlertAuditAction.GET, - savedObject: { type: 'alert', id }, + savedObject: { type: 'rule', id }, error, }) ); @@ -369,7 +369,7 @@ export class AlertsClient { this.auditLogger?.log( alertAuditEvent({ action: AlertAuditAction.GET, - savedObject: { type: 'alert', id }, + savedObject: { type: 'rule', id }, }) ); return this.getAlertFromRaw(result.id, result.attributes, result.references); @@ -414,7 +414,7 @@ export class AlertsClient { this.logger.debug(`getAlertInstanceSummary(): search the event log for alert ${id}`); let events: IEvent[]; try { - const queryResults = await eventLogClient.findEventsBySavedObjectIds('alert', [id], { + const queryResults = await eventLogClient.findEventsBySavedObjectIds('rule', [id], { page: 1, per_page: 10000, start: parsedDateStart.toISOString(), @@ -470,7 +470,7 @@ export class AlertsClient { ? nodeBuilder.and([esKuery.fromKueryExpression(options.filter), authorizationFilter]) : authorizationFilter) ?? options.filter, fields: fields ? this.includeFieldsRequiredForAuthentication(fields) : fields, - type: 'alert', + type: 'rule', }); const authorizedData = data.map(({ id, attributes, references }) => { @@ -480,7 +480,7 @@ export class AlertsClient { this.auditLogger?.log( alertAuditEvent({ action: AlertAuditAction.FIND, - savedObject: { type: 'alert', id }, + savedObject: { type: 'rule', id }, error, }) ); @@ -497,7 +497,7 @@ export class AlertsClient { this.auditLogger?.log( alertAuditEvent({ action: AlertAuditAction.FIND, - savedObject: { type: 'alert', id }, + savedObject: { type: 'rule', id }, }) ) ); @@ -533,7 +533,7 @@ export class AlertsClient { : authorizationFilter) ?? filter, page: 1, perPage: 0, - type: 'alert', + type: 'rule', }); logSuccessfulAuthorization(); @@ -557,7 +557,7 @@ export class AlertsClient { try { const decryptedAlert = await this.encryptedSavedObjectsClient.getDecryptedAsInternalUser( - 'alert', + 'rule', id, { namespace: this.namespace } ); @@ -570,7 +570,7 @@ export class AlertsClient { `delete(): Failed to load API key to invalidate on alert ${id}: ${e.message}` ); // Still attempt to load the scheduledTaskId using SOC - const alert = await this.unsecuredSavedObjectsClient.get('alert', id); + const alert = await this.unsecuredSavedObjectsClient.get('rule', id); taskIdToRemove = alert.attributes.scheduledTaskId; attributes = alert.attributes; } @@ -585,7 +585,7 @@ export class AlertsClient { this.auditLogger?.log( alertAuditEvent({ action: AlertAuditAction.DELETE, - savedObject: { type: 'alert', id }, + savedObject: { type: 'rule', id }, error, }) ); @@ -596,11 +596,11 @@ export class AlertsClient { alertAuditEvent({ action: AlertAuditAction.DELETE, outcome: EventOutcome.UNKNOWN, - savedObject: { type: 'alert', id }, + savedObject: { type: 'rule', id }, }) ); - const removeResult = await this.unsecuredSavedObjectsClient.delete('alert', id); + const removeResult = await this.unsecuredSavedObjectsClient.delete('rule', id); await Promise.all([ taskIdToRemove ? this.taskManager.removeIfExists(taskIdToRemove) : null, @@ -635,7 +635,7 @@ export class AlertsClient { try { alertSavedObject = await this.encryptedSavedObjectsClient.getDecryptedAsInternalUser( - 'alert', + 'rule', id, { namespace: this.namespace } ); @@ -645,7 +645,7 @@ export class AlertsClient { `update(): Failed to load API key to invalidate on alert ${id}: ${e.message}` ); // Still attempt to load the object using SOC - alertSavedObject = await this.unsecuredSavedObjectsClient.get('alert', id); + alertSavedObject = await this.unsecuredSavedObjectsClient.get('rule', id); } try { @@ -658,7 +658,7 @@ export class AlertsClient { this.auditLogger?.log( alertAuditEvent({ action: AlertAuditAction.UPDATE, - savedObject: { type: 'alert', id }, + savedObject: { type: 'rule', id }, error, }) ); @@ -669,7 +669,7 @@ export class AlertsClient { alertAuditEvent({ action: AlertAuditAction.UPDATE, outcome: EventOutcome.UNKNOWN, - savedObject: { type: 'alert', id }, + savedObject: { type: 'rule', id }, }) ); @@ -743,7 +743,7 @@ export class AlertsClient { }); try { updatedObject = await this.unsecuredSavedObjectsClient.create( - 'alert', + 'rule', createAttributes, { id, @@ -795,7 +795,7 @@ export class AlertsClient { try { const decryptedAlert = await this.encryptedSavedObjectsClient.getDecryptedAsInternalUser( - 'alert', + 'rule', id, { namespace: this.namespace } ); @@ -808,7 +808,7 @@ export class AlertsClient { `updateApiKey(): Failed to load API key to invalidate on alert ${id}: ${e.message}` ); // Still attempt to load the attributes and version using SOC - const alert = await this.unsecuredSavedObjectsClient.get('alert', id); + const alert = await this.unsecuredSavedObjectsClient.get('rule', id); attributes = alert.attributes; version = alert.version; } @@ -826,7 +826,7 @@ export class AlertsClient { this.auditLogger?.log( alertAuditEvent({ action: AlertAuditAction.UPDATE_API_KEY, - savedObject: { type: 'alert', id }, + savedObject: { type: 'rule', id }, error, }) ); @@ -848,14 +848,14 @@ export class AlertsClient { alertAuditEvent({ action: AlertAuditAction.UPDATE_API_KEY, outcome: EventOutcome.UNKNOWN, - savedObject: { type: 'alert', id }, + savedObject: { type: 'rule', id }, }) ); this.alertTypeRegistry.ensureAlertTypeEnabled(attributes.alertTypeId); try { - await this.unsecuredSavedObjectsClient.update('alert', id, updateAttributes, { version }); + await this.unsecuredSavedObjectsClient.update('rule', id, updateAttributes, { version }); } catch (e) { // Avoid unused API key markApiKeyForInvalidation( @@ -890,7 +890,7 @@ export class AlertsClient { try { const decryptedAlert = await this.encryptedSavedObjectsClient.getDecryptedAsInternalUser( - 'alert', + 'rule', id, { namespace: this.namespace } ); @@ -903,7 +903,7 @@ export class AlertsClient { `enable(): Failed to load API key to invalidate on alert ${id}: ${e.message}` ); // Still attempt to load the attributes and version using SOC - const alert = await this.unsecuredSavedObjectsClient.get('alert', id); + const alert = await this.unsecuredSavedObjectsClient.get('rule', id); attributes = alert.attributes; version = alert.version; } @@ -922,7 +922,7 @@ export class AlertsClient { this.auditLogger?.log( alertAuditEvent({ action: AlertAuditAction.ENABLE, - savedObject: { type: 'alert', id }, + savedObject: { type: 'rule', id }, error, }) ); @@ -933,7 +933,7 @@ export class AlertsClient { alertAuditEvent({ action: AlertAuditAction.ENABLE, outcome: EventOutcome.UNKNOWN, - savedObject: { type: 'alert', id }, + savedObject: { type: 'rule', id }, }) ); @@ -952,7 +952,7 @@ export class AlertsClient { updatedAt: new Date().toISOString(), }); try { - await this.unsecuredSavedObjectsClient.update('alert', id, updateAttributes, { version }); + await this.unsecuredSavedObjectsClient.update('rule', id, updateAttributes, { version }); } catch (e) { // Avoid unused API key markApiKeyForInvalidation( @@ -967,7 +967,7 @@ export class AlertsClient { attributes.alertTypeId, attributes.schedule as IntervalSchedule ); - await this.unsecuredSavedObjectsClient.update('alert', id, { + await this.unsecuredSavedObjectsClient.update('rule', id, { scheduledTaskId: scheduledTask.id, }); if (apiKeyToInvalidate) { @@ -995,7 +995,7 @@ export class AlertsClient { try { const decryptedAlert = await this.encryptedSavedObjectsClient.getDecryptedAsInternalUser( - 'alert', + 'rule', id, { namespace: this.namespace } ); @@ -1008,7 +1008,7 @@ export class AlertsClient { `disable(): Failed to load API key to invalidate on alert ${id}: ${e.message}` ); // Still attempt to load the attributes and version using SOC - const alert = await this.unsecuredSavedObjectsClient.get('alert', id); + const alert = await this.unsecuredSavedObjectsClient.get('rule', id); attributes = alert.attributes; version = alert.version; } @@ -1023,7 +1023,7 @@ export class AlertsClient { this.auditLogger?.log( alertAuditEvent({ action: AlertAuditAction.DISABLE, - savedObject: { type: 'alert', id }, + savedObject: { type: 'rule', id }, error, }) ); @@ -1034,7 +1034,7 @@ export class AlertsClient { alertAuditEvent({ action: AlertAuditAction.DISABLE, outcome: EventOutcome.UNKNOWN, - savedObject: { type: 'alert', id }, + savedObject: { type: 'rule', id }, }) ); @@ -1042,7 +1042,7 @@ export class AlertsClient { if (attributes.enabled === true) { await this.unsecuredSavedObjectsClient.update( - 'alert', + 'rule', id, this.updateMeta({ ...attributes, @@ -1081,7 +1081,7 @@ export class AlertsClient { private async muteAllWithOCC({ id }: { id: string }) { const { attributes, version } = await this.unsecuredSavedObjectsClient.get( - 'alert', + 'rule', id ); @@ -1099,7 +1099,7 @@ export class AlertsClient { this.auditLogger?.log( alertAuditEvent({ action: AlertAuditAction.MUTE, - savedObject: { type: 'alert', id }, + savedObject: { type: 'rule', id }, error, }) ); @@ -1110,7 +1110,7 @@ export class AlertsClient { alertAuditEvent({ action: AlertAuditAction.MUTE, outcome: EventOutcome.UNKNOWN, - savedObject: { type: 'alert', id }, + savedObject: { type: 'rule', id }, }) ); @@ -1142,7 +1142,7 @@ export class AlertsClient { private async unmuteAllWithOCC({ id }: { id: string }) { const { attributes, version } = await this.unsecuredSavedObjectsClient.get( - 'alert', + 'rule', id ); @@ -1160,7 +1160,7 @@ export class AlertsClient { this.auditLogger?.log( alertAuditEvent({ action: AlertAuditAction.UNMUTE, - savedObject: { type: 'alert', id }, + savedObject: { type: 'rule', id }, error, }) ); @@ -1171,7 +1171,7 @@ export class AlertsClient { alertAuditEvent({ action: AlertAuditAction.UNMUTE, outcome: EventOutcome.UNKNOWN, - savedObject: { type: 'alert', id }, + savedObject: { type: 'rule', id }, }) ); @@ -1203,7 +1203,7 @@ export class AlertsClient { private async muteInstanceWithOCC({ alertId, alertInstanceId }: MuteOptions) { const { attributes, version } = await this.unsecuredSavedObjectsClient.get( - 'alert', + 'rule', alertId ); @@ -1221,7 +1221,7 @@ export class AlertsClient { this.auditLogger?.log( alertAuditEvent({ action: AlertAuditAction.MUTE_INSTANCE, - savedObject: { type: 'alert', id: alertId }, + savedObject: { type: 'rule', id: alertId }, error, }) ); @@ -1232,7 +1232,7 @@ export class AlertsClient { alertAuditEvent({ action: AlertAuditAction.MUTE_INSTANCE, outcome: EventOutcome.UNKNOWN, - savedObject: { type: 'alert', id: alertId }, + savedObject: { type: 'rule', id: alertId }, }) ); @@ -1242,7 +1242,7 @@ export class AlertsClient { if (!attributes.muteAll && !mutedInstanceIds.includes(alertInstanceId)) { mutedInstanceIds.push(alertInstanceId); await this.unsecuredSavedObjectsClient.update( - 'alert', + 'rule', alertId, this.updateMeta({ mutedInstanceIds, @@ -1270,7 +1270,7 @@ export class AlertsClient { alertInstanceId: string; }) { const { attributes, version } = await this.unsecuredSavedObjectsClient.get( - 'alert', + 'rule', alertId ); @@ -1287,7 +1287,7 @@ export class AlertsClient { this.auditLogger?.log( alertAuditEvent({ action: AlertAuditAction.UNMUTE_INSTANCE, - savedObject: { type: 'alert', id: alertId }, + savedObject: { type: 'rule', id: alertId }, error, }) ); @@ -1298,7 +1298,7 @@ export class AlertsClient { alertAuditEvent({ action: AlertAuditAction.UNMUTE_INSTANCE, outcome: EventOutcome.UNKNOWN, - savedObject: { type: 'alert', id: alertId }, + savedObject: { type: 'rule', id: alertId }, }) ); @@ -1307,7 +1307,7 @@ export class AlertsClient { const mutedInstanceIds = attributes.mutedInstanceIds || []; if (!attributes.muteAll && mutedInstanceIds.includes(alertInstanceId)) { await this.unsecuredSavedObjectsClient.update( - 'alert', + 'rule', alertId, this.updateMeta({ updatedBy: await this.getUserName(), diff --git a/x-pack/plugins/alerts/server/alerts_client_factory.ts b/x-pack/plugins/alerts/server/alerts_client_factory.ts index 05e50346f56cf5..cca543c1b58216 100644 --- a/x-pack/plugins/alerts/server/alerts_client_factory.ts +++ b/x-pack/plugins/alerts/server/alerts_client_factory.ts @@ -98,7 +98,7 @@ export class AlertsClientFactory { alertTypeRegistry: this.alertTypeRegistry, unsecuredSavedObjectsClient: savedObjects.getScopedClient(request, { excludedWrappers: ['security'], - includedHiddenTypes: ['alert', 'api_key_pending_invalidation'], + includedHiddenTypes: ['rule', 'api_key_pending_invalidation'], }), authorization, actionsAuthorization: actions.getActionsAuthorizationWithRequest(request), diff --git a/x-pack/plugins/alerts/server/health/get_health.ts b/x-pack/plugins/alerts/server/health/get_health.ts index f00e79a0d96ea9..fc79cb0a6fc238 100644 --- a/x-pack/plugins/alerts/server/health/get_health.ts +++ b/x-pack/plugins/alerts/server/health/get_health.ts @@ -27,9 +27,9 @@ export const getHealth = async ( }; const { saved_objects: decryptErrorData } = await internalSavedObjectsRepository.find({ - filter: `alert.attributes.executionStatus.status:error and alert.attributes.executionStatus.error.reason:${AlertExecutionStatusErrorReasons.Decrypt}`, + filter: `rule.attributes.executionStatus.status:error and rule.attributes.executionStatus.error.reason:${AlertExecutionStatusErrorReasons.Decrypt}`, fields: ['executionStatus'], - type: 'alert', + type: 'rule', sortField: 'executionStatus.lastExecutionDate', sortOrder: 'desc', page: 1, @@ -44,9 +44,9 @@ export const getHealth = async ( } const { saved_objects: executeErrorData } = await internalSavedObjectsRepository.find({ - filter: `alert.attributes.executionStatus.status:error and alert.attributes.executionStatus.error.reason:${AlertExecutionStatusErrorReasons.Execute}`, + filter: `rule.attributes.executionStatus.status:error and rule.attributes.executionStatus.error.reason:${AlertExecutionStatusErrorReasons.Execute}`, fields: ['executionStatus'], - type: 'alert', + type: 'rule', sortField: 'executionStatus.lastExecutionDate', sortOrder: 'desc', page: 1, @@ -61,9 +61,9 @@ export const getHealth = async ( } const { saved_objects: readErrorData } = await internalSavedObjectsRepository.find({ - filter: `alert.attributes.executionStatus.status:error and alert.attributes.executionStatus.error.reason:${AlertExecutionStatusErrorReasons.Read}`, + filter: `rule.attributes.executionStatus.status:error and rule.attributes.executionStatus.error.reason:${AlertExecutionStatusErrorReasons.Read}`, fields: ['executionStatus'], - type: 'alert', + type: 'rule', sortField: 'executionStatus.lastExecutionDate', sortOrder: 'desc', page: 1, @@ -78,9 +78,9 @@ export const getHealth = async ( } const { saved_objects: noErrorData } = await internalSavedObjectsRepository.find({ - filter: 'not alert.attributes.executionStatus.status:error', + filter: 'not rule.attributes.executionStatus.status:error', fields: ['executionStatus'], - type: 'alert', + type: 'rule', sortField: 'executionStatus.lastExecutionDate', sortOrder: 'desc', }); diff --git a/x-pack/plugins/alerts/server/health/task.ts b/x-pack/plugins/alerts/server/health/task.ts index a6f1237c435836..134bc6c44c36e9 100644 --- a/x-pack/plugins/alerts/server/health/task.ts +++ b/x-pack/plugins/alerts/server/health/task.ts @@ -72,7 +72,7 @@ export function healthCheckTaskRunner( async run() { try { const alertingHealthStatus = await getHealth( - (await coreStartServices)[0].savedObjects.createInternalRepository(['alert']) + (await coreStartServices)[0].savedObjects.createInternalRepository(['rule']) ); return { state: { diff --git a/x-pack/plugins/alerts/server/plugin.ts b/x-pack/plugins/alerts/server/plugin.ts index 8dba4453d56827..21f939688d5a6a 100644 --- a/x-pack/plugins/alerts/server/plugin.ts +++ b/x-pack/plugins/alerts/server/plugin.ts @@ -322,7 +322,7 @@ export class AlertingPlugin { licenseState?.setNotifyUsage(plugins.licensing.featureUsage.notifyUsage); const encryptedSavedObjectsClient = plugins.encryptedSavedObjects.getClient({ - includedHiddenTypes: ['alert'], + includedHiddenTypes: ['rule'], }); const spaceIdToNamespace = (spaceId?: string) => { @@ -369,11 +369,11 @@ export class AlertingPlugin { encryptedSavedObjectsClient, basePathService: core.http.basePath, eventLogger: this.eventLogger!, - internalSavedObjectsRepository: core.savedObjects.createInternalRepository(['alert']), + internalSavedObjectsRepository: core.savedObjects.createInternalRepository(['rule']), alertTypeRegistry: this.alertTypeRegistry!, }); - this.eventLogService!.registerSavedObjectProvider('alert', (request) => { + this.eventLogService!.registerSavedObjectProvider('rule', (request) => { const client = getAlertsClientWithRequest(request); return (objects?: SavedObjectsBulkGetObject[]) => objects @@ -390,7 +390,7 @@ export class AlertingPlugin { listTypes: alertTypeRegistry!.list.bind(this.alertTypeRegistry!), getAlertsClientWithRequest, getFrameworkHealth: async () => - await getHealth(core.savedObjects.createInternalRepository(['alert'])), + await getHealth(core.savedObjects.createInternalRepository(['rule'])), }; } @@ -406,7 +406,7 @@ export class AlertingPlugin { }, listTypes: alertTypeRegistry!.list.bind(alertTypeRegistry!), getFrameworkHealth: async () => - await getHealth(savedObjects.createInternalRepository(['alert'])), + await getHealth(savedObjects.createInternalRepository(['rule'])), }; }; }; @@ -429,7 +429,7 @@ export class AlertingPlugin { savedObjects: SavedObjectsServiceStart, request: KibanaRequest ) { - return savedObjects.getScopedClient(request, { includedHiddenTypes: ['alert', 'action'] }); + return savedObjects.getScopedClient(request, { includedHiddenTypes: ['rule', 'action'] }); } public stop() { diff --git a/x-pack/plugins/alerts/server/saved_objects/index.ts b/x-pack/plugins/alerts/server/saved_objects/index.ts index bb4383083fedc5..6c7701543f3475 100644 --- a/x-pack/plugins/alerts/server/saved_objects/index.ts +++ b/x-pack/plugins/alerts/server/saved_objects/index.ts @@ -44,6 +44,12 @@ export function setupSavedObjects( migrations: getMigrations(encryptedSavedObjects), mappings: mappings.alert, }); + savedObjects.registerType({ + name: 'rule', + hidden: true, + namespaceType: 'single', + mappings: mappings.alert, + }); savedObjects.registerType({ name: 'api_key_pending_invalidation', diff --git a/x-pack/plugins/alerts/server/saved_objects/migrations.ts b/x-pack/plugins/alerts/server/saved_objects/migrations.ts index e89903affff93f..8113650488649c 100644 --- a/x-pack/plugins/alerts/server/saved_objects/migrations.ts +++ b/x-pack/plugins/alerts/server/saved_objects/migrations.ts @@ -41,14 +41,24 @@ export function getMigrations( RawAlert, RawAlert >( - // migrate all documents in 7.11 in order to add the "updatedAt" and "notifyWhen" fields + // migrate all documents in 7.12 in order to add the "updatedAt" and "notifyWhen" fields (doc): doc is SavedObjectUnsanitizedDoc => true, pipeMigrations(setAlertUpdatedAtDate, setNotifyWhen) ); + const migrationAlertToRule = encryptedSavedObjects.createMigration< + RawAlert, + RawAlert + >( + // migrate all documents in 7.12 in order to turn them into rules + (doc): doc is SavedObjectUnsanitizedDoc => true, + convertAlertIntoRule + ); + return { '7.10.0': executeMigrationWithErrorHandling(migrationWhenRBACWasIntroduced, '7.10.0'), '7.11.0': executeMigrationWithErrorHandling(migrationAlertUpdatedAtAndNotifyWhen, '7.11.0'), + '7.12.0': executeMigrationWithErrorHandling(migrationAlertToRule, '7.12.0'), }; } @@ -95,6 +105,20 @@ const setNotifyWhen = ( }; }; +const convertAlertIntoRule = ( + { migrationVersion, ...doc}: SavedObjectUnsanitizedDoc +): SavedObjectUnsanitizedDoc => { + console.log(`=-=-=-=-=-=-=-=-=-=-=-`) + console.log(`=-=-=-=-=-=-=-=-=-=-=-`) + console.log(JSON.stringify(doc)) + console.log(`=-=-=-=-=-=-=-=-=-=-=-`) + console.log(`=-=-=-=-=-=-=-=-=-=-=-`) + return { + ...doc, + type: 'rule' + }; +}; + const consumersToChange: Map = new Map( Object.entries({ alerting: 'alerts', diff --git a/x-pack/plugins/alerts/server/saved_objects/partially_update_alert.ts b/x-pack/plugins/alerts/server/saved_objects/partially_update_alert.ts index 324f07e445e628..0851cdb9a13361 100644 --- a/x-pack/plugins/alerts/server/saved_objects/partially_update_alert.ts +++ b/x-pack/plugins/alerts/server/saved_objects/partially_update_alert.ts @@ -43,7 +43,7 @@ export async function partiallyUpdateAlert( const updateOptions: SavedObjectsUpdateOptions = pick(options, 'namespace', 'version', 'refresh'); try { - await savedObjectsClient.update('alert', id, attributeUpdates, updateOptions); + await savedObjectsClient.update('rule', id, attributeUpdates, updateOptions); } catch (err) { if (options?.ignore404 && SavedObjectsErrorHelpers.isNotFoundError(err)) { return; diff --git a/x-pack/plugins/alerts/server/task_runner/create_execution_handler.ts b/x-pack/plugins/alerts/server/task_runner/create_execution_handler.ts index ad024d7ddd8841..9f6bf0e052522b 100644 --- a/x-pack/plugins/alerts/server/task_runner/create_execution_handler.ts +++ b/x-pack/plugins/alerts/server/task_runner/create_execution_handler.ts @@ -161,7 +161,7 @@ export function createExecutionHandler< apiKey: apiKey ?? null, source: asSavedObjectExecutionSource({ id: alertId, - type: 'alert', + type: 'rule', }), }); @@ -176,7 +176,7 @@ export function createExecutionHandler< action_subgroup: actionSubgroup, }, saved_objects: [ - { rel: SAVED_OBJECT_REL_PRIMARY, type: 'alert', id: alertId, ...namespace }, + { rel: SAVED_OBJECT_REL_PRIMARY, type: 'rule', id: alertId, ...namespace }, { type: 'action', id: action.id, ...namespace }, ], }, diff --git a/x-pack/plugins/alerts/server/task_runner/task_runner.ts b/x-pack/plugins/alerts/server/task_runner/task_runner.ts index 42708c9b7eb54b..3a5cb7bdbd3125 100644 --- a/x-pack/plugins/alerts/server/task_runner/task_runner.ts +++ b/x-pack/plugins/alerts/server/task_runner/task_runner.ts @@ -110,7 +110,7 @@ export class TaskRunner< const { attributes: { apiKey }, } = await this.context.encryptedSavedObjectsClient.getDecryptedAsInternalUser( - 'alert', + 'rule', alertId, { namespace } ); @@ -460,7 +460,7 @@ export class TaskRunner< saved_objects: [ { rel: SAVED_OBJECT_REL_PRIMARY, - type: 'alert', + type: 'rule', id: alertId, namespace, }, @@ -629,7 +629,7 @@ function generateNewAndRecoveredInstanceEvents< saved_objects: [ { rel: SAVED_OBJECT_REL_PRIMARY, - type: 'alert', + type: 'rule', id: alertId, namespace, }, diff --git a/x-pack/plugins/alerts/server/usage/alerts_telemetry.ts b/x-pack/plugins/alerts/server/usage/alerts_telemetry.ts index 5165307fd43e98..de69a938eee93a 100644 --- a/x-pack/plugins/alerts/server/usage/alerts_telemetry.ts +++ b/x-pack/plugins/alerts/server/usage/alerts_telemetry.ts @@ -219,7 +219,7 @@ export async function getTotalCountAggregations(callCluster: LegacyAPICaller, ki body: { query: { bool: { - filter: [{ term: { type: 'alert' } }], + filter: [{ term: { type: 'rule' } }], }, }, aggs: { @@ -228,7 +228,7 @@ export async function getTotalCountAggregations(callCluster: LegacyAPICaller, ki intervalTime: intervalTimeMetric, connectorsAgg: { nested: { - path: 'alert.actions', + path: 'rule.actions', }, aggs: { connectors: connectorsMetric, @@ -292,7 +292,7 @@ export async function getTotalCountInUse(callCluster: LegacyAPICaller, kibanaIne body: { query: { bool: { - filter: [{ term: { type: 'alert' } }, { term: { 'alert.enabled': true } }], + filter: [{ term: { type: 'rule' } }, { term: { 'rule.enabled': true } }], }, }, aggs: { diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/index.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/index.ts index c1050d26e083ba..fcee0594b5c35d 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/index.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/index.ts @@ -10,7 +10,7 @@ import { buildUp, tearDown } from '..'; // eslint-disable-next-line import/no-default-export export default function alertingTests({ loadTestFile, getService }: FtrProviderContext) { - describe('Alerting', () => { + describe.only('Alerting', () => { before(async () => buildUp(getService)); after(async () => tearDown(getService)); diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/migrations.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/migrations.ts index 0e3ec894ff3932..d789099ee676c1 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/migrations.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/alerting/migrations.ts @@ -14,7 +14,7 @@ export default function createGetTests({ getService }: FtrProviderContext) { const supertest = getService('supertest'); const esArchiver = getService('esArchiver'); - describe('migrations', () => { + describe.only('migrations', () => { before(async () => { await esArchiver.load('alerts'); }); diff --git a/x-pack/test/alerting_api_integration/spaces_only/tests/index.ts b/x-pack/test/alerting_api_integration/spaces_only/tests/index.ts index 711910c13023da..0d6aaff2f944d0 100644 --- a/x-pack/test/alerting_api_integration/spaces_only/tests/index.ts +++ b/x-pack/test/alerting_api_integration/spaces_only/tests/index.ts @@ -10,7 +10,7 @@ import { Spaces } from '../scenarios'; // eslint-disable-next-line import/no-default-export export default function alertingApiIntegrationTests({ loadTestFile }: FtrProviderContext) { - describe('alerting api integration spaces only', function () { + describe.only('alerting api integration spaces only', function () { this.tags('ciGroup12'); loadTestFile(require.resolve('./actions'));