diff --git a/src/apis/pagerduty.ts b/src/apis/pagerduty.ts index 8077b35..5903e98 100644 --- a/src/apis/pagerduty.ts +++ b/src/apis/pagerduty.ts @@ -22,7 +22,8 @@ import { PagerDutyServicesAPIResponse, PagerDutyAccountConfig, PagerDutyIntegrationResponse, - PagerDutyAccountConfig + PagerDutyServiceDependency, + PagerDutyServiceDependencyResponse, } from '@pagerduty/backstage-plugin-common'; import { DateTime } from 'luxon'; @@ -102,6 +103,155 @@ function getApiBaseUrl(account?: string): string { } // Supporting router +export async function addServiceRelationsToService(serviceRelations: PagerDutyServiceDependency[], account?: string): Promise { + let response: Response; + const options: RequestInit = { + method: 'POST', + headers: { + Authorization: await getAuthToken(account), + 'Accept': 'application/vnd.pagerduty+json;version=2', + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + relationships: serviceRelations + }) + }; + + const apiBaseUrl = getApiBaseUrl(account); + const baseUrl = `${apiBaseUrl}/service_dependencies/associate`; + + try { + response = await fetchWithRetries(baseUrl, options); + } catch (error) { + throw new Error(`Failed to retrieve service dependencies: ${error}`); + } + + if (response.status >= 500) { + throw new HttpError(`Failed to add service dependencies. PagerDuty API returned a server error. Retrying with the same arguments will not work.`, response.status); + } + + switch (response.status) { + case 400: + throw new HttpError("Failed to add service dependencies. Caller provided invalid arguments. Please review the response for error details. Retrying with the same arguments will not work.", 400); + case 401: + throw new HttpError("Failed to add service dependencies. Caller did not supply credentials or did not provide the correct credentials. If you are using an API key, it may be invalid or your Authorization header may be malformed.", 401); + case 403: + throw new HttpError("Failed to add service dependencies. Caller is not authorized to view the requested resource. While your authentication is valid, the authenticated user or token does not have permission to perform this action.", 403); + case 404: + throw new HttpError("Failed to add service dependencies. The requested resource was not found.", 404); + default: // 200 + break; + } + + let result: PagerDutyServiceDependencyResponse; + try { + result = await response.json(); + + return result.relationships; + + } catch (error) { + throw new HttpError(`Failed to parse service dependency information: ${error}`, 500); + } +} + +export async function removeServiceRelationsFromService(serviceRelations: PagerDutyServiceDependency[], account?: string): Promise { + let response: Response; + const options: RequestInit = { + method: 'POST', + headers: { + Authorization: await getAuthToken(account), + 'Accept': 'application/vnd.pagerduty+json;version=2', + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + relationships: serviceRelations + }) + }; + + const apiBaseUrl = getApiBaseUrl(account); + const baseUrl = `${apiBaseUrl}/service_dependencies/disassociate`; + + try { + response = await fetchWithRetries(`${baseUrl}`, options); + } catch (error) { + throw new Error(`Failed to retrieve service dependencies: ${error}`); + } + + if (response.status >= 500) { + throw new HttpError(`Failed to remove service dependencies. PagerDuty API returned a server error. Retrying with the same arguments will not work.`, response.status); + } + + switch (response.status) { + case 400: + throw new HttpError("Failed to remove service dependencies. Caller provided invalid arguments. Please review the response for error details. Retrying with the same arguments will not work.", 400); + case 401: + throw new HttpError("Failed to remove service dependencies. Caller did not supply credentials or did not provide the correct credentials. If you are using an API key, it may be invalid or your Authorization header may be malformed.", 401); + case 403: + throw new HttpError("Failed to remove service dependencies. Caller is not authorized to view the requested resource. While your authentication is valid, the authenticated user or token does not have permission to perform this action.", 403); + case 404: + throw new HttpError("Failed to remove service dependencies. The requested resource was not found.", 404); + default: // 200 + break; + } + + let result: PagerDutyServiceDependencyResponse; + try { + result = await response.json(); + + return result.relationships; + + } catch (error) { + throw new HttpError(`Failed to parse service dependency information: ${error}`, 500); + } +} + +export async function getServiceRelationshipsById(serviceId: string, account?: string): Promise { + let response: Response; + const options: RequestInit = { + method: 'GET', + headers: { + Authorization: await getAuthToken(account), + 'Accept': 'application/vnd.pagerduty+json;version=2', + 'Content-Type': 'application/json', + }, + }; + + const apiBaseUrl = getApiBaseUrl(account); + const baseUrl = `${apiBaseUrl}/service_dependencies/technical_services/${serviceId}`; + + try { + response = await fetchWithRetries(baseUrl, options); + } catch (error) { + throw new Error(`Failed to retrieve service dependencies: ${error}`); + } + + if (response.status >= 500) { + throw new HttpError(`Failed to list service dependencies. PagerDuty API returned a server error. Retrying with the same arguments will not work.`, response.status); + } + + switch (response.status) { + case 400: + throw new HttpError("Failed to list service dependencies. Caller provided invalid arguments. Please review the response for error details. Retrying with the same arguments will not work.", 400); + case 401: + throw new HttpError("Failed to list service dependencies. Caller did not supply credentials or did not provide the correct credentials. If you are using an API key, it may be invalid or your Authorization header may be malformed.", 401); + case 403: + throw new HttpError("Failed to list service dependencies. Caller is not authorized to view the requested resource. While your authentication is valid, the authenticated user or token does not have permission to perform this action.", 403); + case 404: + throw new HttpError("Failed to list service dependencies. The requested resource was not found.", 404); + default: // 200 + break; + } + + let result: PagerDutyServiceDependencyResponse; + try { + result = await response.json(); + + return result.relationships; + } catch (error) { + throw new HttpError(`Failed to parse service dependency information: ${error}`, 500); + } +} + async function getEscalationPolicies(offset: number, limit: number, account?: string): Promise<[Boolean, PagerDutyEscalationPolicy[]]> { let response: Response; @@ -119,11 +269,15 @@ async function getEscalationPolicies(offset: number, limit: number, account?: st const baseUrl = `${apiBaseUrl}/escalation_policies`; try { - response = await fetch(`${baseUrl}?${params}`, options); + response = await fetchWithRetries(`${baseUrl}?${params}`, options); } catch (error) { throw new Error(`Failed to retrieve escalation policies: ${error}`); } + if (response.status >= 500) { + throw new HttpError(`Failed to list escalation policies. PagerDuty API returned a server error. Retrying with the same arguments will not work.`, response.status); + } + switch (response.status) { case 400: throw new HttpError("Failed to list escalation policies. Caller provided invalid arguments.", 400); @@ -208,11 +362,15 @@ export async function isEventNoiseReductionEnabled(account?: string): Promise= 500) { + throw new HttpError(`Failed to read abilities. PagerDuty API returned a server error. Retrying with the same arguments will not work.`, response.status); + } + switch (response.status) { case 401: throw new Error(`Failed to read abilities. Caller did not supply credentials or did not provide the correct credentials.`); @@ -256,11 +414,15 @@ export async function getOncallUsers(escalationPolicy: string, account?: string) const baseUrl = `${apiBaseUrl}/oncalls`; try { - response = await fetch(`${baseUrl}?${params}`, options); + response = await fetchWithRetries(`${baseUrl}?${params}`, options); } catch (error) { throw new Error(`Failed to retrieve oncalls: ${error}`); } + if (response.status >= 500) { + throw new HttpError(`Failed to list oncalls. PagerDuty API returned a server error. Retrying with the same arguments will not work.`, response.status); + } + switch (response.status) { case 400: throw new HttpError("Failed to list oncalls. Caller provided invalid arguments.", 400); @@ -332,11 +494,15 @@ export async function getServiceById(serviceId: string, account?: string): Promi const baseUrl = `${apiBaseUrl}/services`; try { - response = await fetch(`${baseUrl}/${serviceId}?${params}`, options); + response = await fetchWithRetries(`${baseUrl}/${serviceId}?${params}`, options); } catch (error) { throw new Error(`Failed to retrieve service: ${error}`); } + if (response.status >= 500) { + throw new HttpError(`Failed to get service. PagerDuty API returned a server error. Retrying with the same arguments will not work.`, response.status); + } + switch (response.status) { case 400: throw new HttpError("Failed to get service. Caller provided invalid arguments.", 400); @@ -378,11 +544,15 @@ export async function getServiceByIntegrationKey(integrationKey: string, account const baseUrl = `${apiBaseUrl}/services`; try { - response = await fetch(`${baseUrl}?${params}`, options); + response = await fetchWithRetries(`${baseUrl}?${params}`, options); } catch (error) { throw new Error(`Failed to retrieve service: ${error}`); } + if (response.status >= 500) { + throw new HttpError(`Failed to get service. PagerDuty API returned a server error. Retrying with the same arguments will not work.`, response.status); + } + switch (response.status) { case 400: throw new HttpError("Failed to get service. Caller provided invalid arguments.", 400); @@ -440,7 +610,11 @@ export async function getAllServices(): Promise { do { const paginatedUrl = `${baseUrl}?${params}&offset=${offset}&limit=${limit}`; - response = await fetch(paginatedUrl, options); + response = await fetchWithRetries(paginatedUrl, options); + + if (response.status >= 500) { + throw new HttpError(`Failed to get services. PagerDuty API returned a server error. Retrying with the same arguments will not work.`, response.status); + } switch (response.status) { case 400: @@ -489,11 +663,15 @@ export async function getChangeEvents(serviceId: string, account?: string): Prom const baseUrl = `${apiBaseUrl}/services`; try { - response = await fetch(`${baseUrl}/${serviceId}/change_events?${params}`, options); + response = await fetchWithRetries(`${baseUrl}/${serviceId}/change_events?${params}`, options); } catch (error) { throw new Error(`Failed to retrieve change events for service: ${error}`); } + if (response.status >= 500) { + throw new HttpError(`Failed to get change events for service. PagerDuty API returned a server error. Retrying with the same arguments will not work.`, response.status); + } + switch (response.status) { case 400: throw new HttpError("Failed to get change events for service. Caller provided invalid arguments.", 400); @@ -534,11 +712,15 @@ export async function getIncidents(serviceId: string, account?: string): Promise const baseUrl = `${apiBaseUrl}/incidents`; try { - response = await fetch(`${baseUrl}?${params}`, options); + response = await fetchWithRetries(`${baseUrl}?${params}`, options); } catch (error) { throw new Error(`Failed to retrieve incidents for service: ${error}`); } + if (response.status >= 500) { + throw new HttpError(`Failed to get incidents for service. PagerDuty API returned a server error. Retrying with the same arguments will not work.`, response.status); + } + switch (response.status) { case 400: throw new HttpError("Failed to get incidents for service. Caller provided invalid arguments.", 400); @@ -580,11 +762,15 @@ export async function getServiceStandards(serviceId: string, account?: string): const baseUrl = `${apiBaseUrl}/standards/scores/technical_services/${serviceId}`; try { - response = await fetch(baseUrl, options); + response = await fetchWithRetries(baseUrl, options); } catch (error) { throw new Error(`Failed to retrieve service standards for service: ${error}`); } + if (response.status >= 500) { + throw new HttpError(`Failed to get service standards for service. PagerDuty API returned a server error. Retrying with the same arguments will not work.`, response.status); + } + switch (response.status) { case 401: throw new HttpError("Failed to get service standards for service. Caller did not supply credentials or did not provide the correct credentials.", 401); @@ -633,11 +819,15 @@ export async function getServiceMetrics(serviceId: string, account?: string): Pr const baseUrl = `${apiBaseUrl}/analytics/metrics/incidents/services`; try { - response = await fetch(baseUrl, options); + response = await fetchWithRetries(baseUrl, options); } catch (error) { throw new Error(`Failed to retrieve service metrics for service: ${error}`); } + if (response.status >= 500) { + throw new HttpError(`Failed to get service metrics for service. PagerDuty API returned a server error. Retrying with the same arguments will not work.`, response.status); + } + switch (response.status) { case 400: throw new HttpError("Failed to get service metrics for service. Caller provided invalid arguments. Please review the response for error details. Retrying with the same arguments will not work.", 400); @@ -692,11 +882,15 @@ export async function createServiceIntegration({ serviceId, vendorId, account }: }; try { - response = await fetch(`${baseUrl}/${serviceId}/integrations`, options); + response = await fetchWithRetries(`${baseUrl}/${serviceId}/integrations`, options); } catch (error) { throw new Error(`Failed to create service integration: ${error}`); } + if (response.status >= 500) { + throw new Error(`Failed to create service integration. PagerDuty API returned a server error. Retrying with the same arguments will not work.`); + } + switch (response.status) { case 400: throw new Error(`Failed to create service integration. Caller provided invalid arguments.`); @@ -721,4 +915,27 @@ export async function createServiceIntegration({ serviceId, vendorId, account }: } } +export async function fetchWithRetries(url: string, options: RequestInit): Promise { + let response: Response; + let error: Error = new Error(); + + // set retry parameters + const maxRetries = 5; + const delay = 1000; + let factor = 2; + + for (let i = 0; i < maxRetries; i++) { + try { + response = await fetch(url, options); + return response; + } catch (e) { + error = e; + } + + const timeout = delay * factor; + await new Promise(resolve => setTimeout(resolve, timeout)); + factor *= 2; + } + throw new Error(`Failed to fetch data after ${maxRetries} retries. Last error: ${error}`); +} diff --git a/src/service/router.test.ts b/src/service/router.test.ts index 58fc5fa..261b436 100644 --- a/src/service/router.test.ts +++ b/src/service/router.test.ts @@ -4,7 +4,7 @@ import express from 'express'; import request from 'supertest'; import { createRouter, createComponentEntitiesReferenceDict, buildEntityMappingsResponse } from './router'; -import { PagerDutyEscalationPolicy, PagerDutyService, PagerDutyServiceResponse, PagerDutyOnCallUsersResponse, PagerDutyChangeEventsResponse, PagerDutyChangeEvent, PagerDutyIncidentsResponse, PagerDutyIncident, PagerDutyServiceStandardsResponse, PagerDutyServiceMetricsResponse, PagerDutyEntityMappingsResponse } from '@pagerduty/backstage-plugin-common'; +import { PagerDutyEscalationPolicy, PagerDutyService, PagerDutyServiceResponse, PagerDutyOnCallUsersResponse, PagerDutyChangeEventsResponse, PagerDutyChangeEvent, PagerDutyIncidentsResponse, PagerDutyIncident, PagerDutyServiceStandardsResponse, PagerDutyServiceMetricsResponse, PagerDutyEntityMappingsResponse, PagerDutyServiceDependencyResponse } from '@pagerduty/backstage-plugin-common'; import { mocked } from "jest-mock"; import fetch, { Response } from "node-fetch"; @@ -85,6 +85,92 @@ describe('createRouter', () => { }); }); + describe('DELETE /dependencies/service/:serviceId', () => { + it.each(testInputs)('returns 400 if dependencies are not provided', async () => { + const response = await request(app).delete('/dependencies/service/12345'); + + expect(response.status).toEqual(400); + expect(response.body).toEqual("Bad Request: 'dependencies' must be provided as part of the request body"); + }); + + it.each(testInputs)('returns 200 if service relations are removed successfully', async () => { + mocked(fetch).mockReturnValue(mockedResponse(200, {})); + + const response = await request(app) + .delete('/dependencies/service/12345') + .send(['dependency1', 'dependency2']); + + expect(response.status).toEqual(200); + }); + }); + + describe('POST /dependencies/service/:serviceId', () => { + it.each(testInputs)('returns 400 if dependencies are not provided', async () => { + const response = await request(app).post('/dependencies/service/12345'); + + expect(response.status).toEqual(400); + expect(response.body).toEqual("Bad Request: 'dependencies' must be provided as part of the request body"); + }); + + it.each(testInputs)('returns 200 if service relations are added successfully', async () => { + mocked(fetch).mockReturnValue(mockedResponse(200, {})); + + const response = await request(app) + .post('/dependencies/service/12345') + .send(['dependency1', 'dependency2']); + + expect(response.status).toEqual(200); + }); + }); + + describe('GET /dependencies/service/:serviceId', () => { + it.each(testInputs)('returns 200 with service relationships if serviceId is valid', async () => { + const mockedResult : PagerDutyServiceDependencyResponse = { + relationships: [ + { + id: "12345", + type: "service_dependency", + dependent_service: { + id: "54321", + type: "technical_service_reference" + }, + supporting_service: { + id: "12345", + type: "technical_service_reference" + } + }, + { + id: "871278", + type: "service_dependency", + dependent_service: { + id: "91292", + type: "technical_service_reference" + }, + supporting_service: { + id: "12345", + type: "technical_service_reference" + } + } + ] + } + + mocked(fetch).mockReturnValue(mockedResponse(200, mockedResult)); + + const response = await request(app).get('/dependencies/service/12345'); + + expect(response.status).toEqual(200); + expect(response.body).toHaveProperty('relationships'); + }); + + it.each(testInputs)('returns 404 if serviceId is not found', async () => { + mocked(fetch).mockReturnValue(mockedResponse(404, {})); + + const response = await request(app).get('/dependencies/service/S3RVICE1D'); + + expect(response.status).toEqual(404); + }); + }); + describe('GET /escalation_policies', () => { it.each(testInputs)('returns ok', async () => { mocked(fetch).mockReturnValue(mockedResponse(200, { diff --git a/src/service/router.ts b/src/service/router.ts index d2f7484..2b2fa09 100644 --- a/src/service/router.ts +++ b/src/service/router.ts @@ -20,10 +20,9 @@ import { getAllServices, loadPagerDutyEndpointsFromConfig, createServiceIntegration, -import { AuthService, DiscoveryService, LoggerService, RootConfigService } from '@backstage/backend-plugin-api'; -import { createLegacyAuthAdapters, errorHandler } from '@backstage/backend-common'; -import { getAllEscalationPolicies, getChangeEvents, getIncidents, getOncallUsers, getServiceById, getServiceByIntegrationKey, getServiceStandards, getServiceMetrics, getAllServices, loadPagerDutyEndpointsFromConfig } from '../apis/pagerduty'; -import { HttpError, PagerDutyChangeEventsResponse, PagerDutyIncidentsResponse, PagerDutyOnCallUsersResponse, PagerDutyServiceResponse, PagerDutyServiceStandardsResponse, PagerDutyServiceMetricsResponse, PagerDutyServicesResponse, PagerDutyEntityMapping, PagerDutyEntityMappingsResponse, PagerDutyService } from '@pagerduty/backstage-plugin-common'; + getServiceRelationshipsById, + addServiceRelationsToService, + removeServiceRelationsFromService } from '../apis/pagerduty'; import { HttpError, @@ -37,6 +36,7 @@ import { PagerDutyEntityMapping, PagerDutyEntityMappingsResponse, PagerDutyService, + PagerDutyServiceDependency, PagerDutySetting } from '@pagerduty/backstage-plugin-common'; import { loadAuthConfig } from '../auth/auth'; @@ -246,6 +246,131 @@ export async function createRouter( // Create the router const router = Router(); router.use(express.json()); + + // DELETE /dependencies/service/:serviceId + router.delete('/dependencies/service/:serviceId', async (request, response) => { + try { + // Get the serviceId from the request parameters + const serviceId = request.params.serviceId || ''; + const account = request.query.account as string || ''; + + if(serviceId === '') { + response.status(400).json("Bad Request: ':serviceId' must be provided as part of the path"); + } + + const dependencies: string[] = Object.keys(request.body).length === 0 ? [] : request.body; + if(!dependencies || dependencies.length === 0) { + response.status(400).json("Bad Request: 'dependencies' must be provided as part of the request body"); + } + + const serviceRelations : PagerDutyServiceDependency[] = []; + + dependencies.forEach(async (dependency) => { + serviceRelations.push({ + supporting_service: { + id: dependency, + type: "service" + }, + dependent_service: { + id: serviceId, + type: "service" + } + }); + }); + + await removeServiceRelationsFromService(serviceRelations, account); + + response.sendStatus(200); + + } catch (error) { + if (error instanceof HttpError) { + logger.error(`Error occurred while processing request: ${error.message}`); + response.status(error.status).json({ + errors: [ + `${error.message}` + ] + }); + } + } + }); + + // POST /dependencies/service/:serviceId + router.post('/dependencies/service/:serviceId', async (request, response) => { + try { + // Get the serviceId from the request parameters + const serviceId = request.params.serviceId || ''; + const account = request.query.account as string || ''; + + if(serviceId === '') { + response.status(400).json("Bad Request: ':serviceId' must be provided as part of the path"); + } + + const dependencies: string[] = Object.keys(request.body).length === 0 ? [] : request.body; + if(!dependencies || dependencies.length === 0) { + response.status(400).json("Bad Request: 'dependencies' must be provided as part of the request body"); + } + + const serviceRelations : PagerDutyServiceDependency[] = []; + + dependencies.forEach(async (dependency) => { + serviceRelations.push({ + supporting_service: { + id: dependency, + type: "service" + }, + dependent_service: { + id: serviceId, + type: "service" + } + }); + }); + + await addServiceRelationsToService(serviceRelations, account); + + response.sendStatus(200); + + } catch (error) { + if (error instanceof HttpError) { + logger.error(`Error occurred while processing request: ${error.message}`); + response.status(error.status).json({ + errors: [ + `${error.message}` + ] + }); + } + } + }); + + + router.get('/dependencies/service/:serviceId', async (request, response) => { + try { + const serviceId = request.params.serviceId; + const account = request.query.account as string || ''; + + if (serviceId) { + const serviceRelationships: PagerDutyServiceDependency[] = await getServiceRelationshipsById(serviceId, account); + + if (serviceRelationships) { + response.json({ + relationships: serviceRelationships + }); + } + } + else { + response.status(400).json("Bad Request: ':serviceId' must be provided as part of the path"); + } + } + catch (error) { + if (error instanceof HttpError) { + response.status(error.status).json({ + errors: [ + `${error.message}` + ] + }); + } + } + }); + // GET /catalog/entity/:entityRef router.get('/catalog/entity/:type/:namespace/:name', async (request, response) => { const type = request.params.type;