Skip to content

Commit

Permalink
Add K8sService as channel and broker subscribers
Browse files Browse the repository at this point in the history
  • Loading branch information
karthikjeeyar committed Dec 15, 2021
1 parent e6dbd1b commit 275f3d4
Show file tree
Hide file tree
Showing 6 changed files with 118 additions and 17 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { useTranslation } from 'react-i18next';
import { K8sResourceKind, k8sCreate } from '@console/internal/module/k8s';
import { getRandomChars } from '@console/shared/src/utils';
import { EventingBrokerModel, EventingTriggerModel, EventingSubscriptionModel } from '../../models';
import { craftResourceKey, sanitizeResourceName } from './pub-sub-utils';
import { pubsubValidationSchema } from './pubsub-validation-utils';
import PubSubModal from './PubSubModal';

Expand Down Expand Up @@ -59,13 +60,14 @@ const PubSub: React.FC<PubSubProps> = ({
ref: {
apiVersion: targetApiVersion,
kind: targetKind,
name: targetName,
name: craftResourceKey(targetName, target),
},
},
},
};

const handleSubmit = (values: FormikValues, action: FormikHelpers<FormikValues>) => {
return k8sCreate(getResourceModel(), values)
return k8sCreate(getResourceModel(), sanitizeResourceName(values))
.then(() => {
action.setStatus({ subscriberAvailable: true, error: '' });
close();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import {
knativeServiceObj,
sampleServices,
} from '../../../topology/__tests__/topology-knative-test-data';
import { RESOURCE_KEY_SEPERATOR, craftResourceKey, getResourceNameFromKey } from '../pub-sub-utils';

describe('pub-sub-utils', () => {
const service = sampleServices.data[0];

describe('craftResourceKey', () => {
it('should return the name if the resource is not having kind and apiversion', () => {
expect(craftResourceKey('test', { metadata: { name: '' } })).toBe(
`${RESOURCE_KEY_SEPERATOR}test`,
);
});

it('should return undefined if the name is not passed', () => {
expect(craftResourceKey('', { metadata: { name: '' } })).toBeUndefined();
});

it('should return a valid resource key', () => {
expect(craftResourceKey('nodejs-ex', service)).toBe('core~v1~Service#nodejs-ex');
});

it('should differentiate k8s service and knative service', () => {
expect(craftResourceKey('nodejs-ex', service)).toBe('core~v1~Service#nodejs-ex');
expect(craftResourceKey('nodejs-ex', knativeServiceObj)).toBe(
'serving.knative.dev~v1~Service#nodejs-ex',
);
});
});
describe('getResourceNameFromKey', () => {
it('should return the name of the resource from the resource key', () => {
expect(getResourceNameFromKey(`${RESOURCE_KEY_SEPERATOR}test`)).toBe('test');
expect(getResourceNameFromKey(`core~v1~Service${RESOURCE_KEY_SEPERATOR}test`)).toBe('test');
expect(
getResourceNameFromKey(`serving.knative.dev~v1~Service${RESOURCE_KEY_SEPERATOR}test`),
).toBe('test');
});

it('should return empty string if invalid argument is passed', () => {
expect(getResourceNameFromKey('')).toBe('');
expect(getResourceNameFromKey(null)).toBe('');
expect(getResourceNameFromKey(undefined)).toBe('');
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ import { useFormikContext, FormikValues } from 'formik';
import * as fuzzy from 'fuzzysearch';
import * as _ from 'lodash';
import { useTranslation } from 'react-i18next';
import { referenceFor } from '@console/internal/module/k8s';
import { ResourceDropdownField, getFieldId } from '@console/shared';
import { getSinkableResources } from '../../../utils/get-knative-resources';
import { craftResourceKey } from '../pub-sub-utils';

const PubSubSubscriber: React.FC = () => {
const { t } = useTranslation();
Expand All @@ -23,7 +23,7 @@ const PubSubSubscriber: React.FC = () => {
setFieldTouched('spec.subscriber.ref.name', true);
setFieldValue('spec.subscriber.ref.name', selectedValue);
if (modelResource) {
const { apiGroup, apiVersion, kind } = modelResource;
const { apiGroup = 'core', apiVersion, kind } = modelResource;
const sinkApiversion = `${apiGroup}/${apiVersion}`;
setFieldValue('spec.subscriber.ref.apiVersion', sinkApiversion);
setFieldTouched('spec.subscriber.ref.apiVersion', true);
Expand Down Expand Up @@ -70,9 +70,7 @@ const PubSubSubscriber: React.FC = () => {
showBadge
autocompleteFilter={autocompleteFilter}
onChange={onSubscriberChange}
customResourceKey={(key: string, resource: any) => {
return key ? `${referenceFor(resource)}-${key}` : undefined;
}}
customResourceKey={craftResourceKey}
autoSelect
disabled={resourceAlert}
onLoad={handleOnLoad}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { FormikValues } from 'formik';
import { K8sResourceKind, referenceFor } from '@console/internal/module/k8s';

export const RESOURCE_KEY_SEPERATOR = '#';

export const craftResourceKey = (key: string, resource: K8sResourceKind): string | undefined =>
key ? `${referenceFor(resource)}${RESOURCE_KEY_SEPERATOR}${key}` : undefined;

export const getResourceNameFromKey = (key: string): string =>
key?.split(RESOURCE_KEY_SEPERATOR).pop() ?? '';

export const sanitizeResourceName = (values: FormikValues): FormikValues => {
const finalValues = { ...values };
finalValues.spec.subscriber.ref.name = getResourceNameFromKey(values.spec.subscriber.ref.name);
return finalValues;
};
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@ import i18next from 'i18next';
import * as _ from 'lodash';
import { WatchK8sResultsObject } from '@console/dynamic-plugin-sdk';
import { getImageForIconClass } from '@console/internal/components/catalog/catalog-item-icon';
import { DeploymentModel, PodModel } from '@console/internal/models';
import { DeploymentModel, PodModel, ServiceModel } from '@console/internal/models';
import {
K8sResourceKind,
apiVersionForModel,
referenceFor,
modelFor,
k8sUpdate,
kindForReference,
apiVersionForReference,
} from '@console/internal/module/k8s';
import { RootState } from '@console/internal/redux';
import { getOwnedResources, OverviewItem } from '@console/shared';
Expand Down Expand Up @@ -185,7 +186,7 @@ const isSubscriber = (
}
return (
subscriberRef &&
referenceFor(resource) === referenceFor(subscriberRef) &&
apiVersionForReference(referenceFor(resource)) === subscriberRef.apiVersion &&
resource.metadata.name === subscriberRef.name
);
};
Expand All @@ -210,7 +211,8 @@ const isPublisher = (
return (
channel &&
channel.name === relatedResource.metadata.name &&
channel.kind === relatedResource.kind
channel.kind === relatedResource.kind &&
channel.apiVersion === relatedResource.apiVersion
);
};

Expand Down Expand Up @@ -246,7 +248,11 @@ export const getSubscribedEventsources = (
getKnativeDynamicResources(resources, eventSourceProps),
(acc, evSrc) => {
const sinkRes = evSrc?.spec?.sink?.ref || {};
if (pubSubResource.kind === sinkRes.kind && pubSubResource.metadata.name === sinkRes.name) {
if (
pubSubResource.kind === sinkRes.kind &&
pubSubResource.metadata.name === sinkRes.name &&
pubSubResource.apiVersion === sinkRes.apiVersion
) {
acc.push(evSrc);
}
return acc;
Expand All @@ -273,6 +279,11 @@ export const getPubSubSubscribers = (
relationshipResource: 'triggers',
isRelatedResource: isSubscriber,
},
{
relatedResource: 'services',
relationshipResource: 'triggers',
isRelatedResource: isSubscriber,
},
],
Service: [
{
Expand All @@ -294,6 +305,11 @@ export const getPubSubSubscribers = (
relationshipResource: 'eventingsubscription',
isRelatedResource: isSubscriber,
},
{
relatedResource: 'services',
relationshipResource: 'eventingsubscription',
isRelatedResource: isSubscriber,
},
];
});

Expand All @@ -307,7 +323,11 @@ export const getPubSubSubscribers = (
_.reduce(
resources[relatedResource].data,
(acc, relRes) => {
if (isInternalResource(relRes) || !isRelatedResource) {
if (
(referenceFor(relRes) !== referenceFor(ServiceModel) &&
isInternalResource(relRes)) ||
!isRelatedResource
) {
return acc;
}
const relationshipResources = (resources[relationshipResource].data || []).filter(
Expand Down Expand Up @@ -583,6 +603,7 @@ export const createPubSubDataItems = (
const knService = _.find(resources?.ksservices?.data, {
metadata: { name: trigger?.spec?.subscriber?.ref?.name },
kind: trigger?.spec?.subscriber?.ref?.kind,
apiVersion: trigger?.spec?.subscriber?.ref?.apiVersion,
});
const knServiceAdded =
knService &&
Expand Down Expand Up @@ -732,10 +753,15 @@ export const getEventTopologyEdgeItems = (resource: K8sResourceKind, { data }):
if (sinkTarget) {
_.forEach(data, (res) => {
const {
apiVersion,
kind,
metadata: { uid: resUid, name: resName },
} = res;
if (resName === sinkTarget.name && kind === sinkTarget.kind) {
if (
resName === sinkTarget.name &&
kind === sinkTarget.kind &&
apiVersion === sinkTarget.apiVersion
) {
edges.push({
id: `${uid}_${resUid}`,
type: EdgeType.EventSource,
Expand All @@ -761,12 +787,15 @@ export const getTriggerTopologyEdgeItems = (broker: K8sResourceKind, resources):
const edges = [];
_.forEach(triggers?.data, (trigger) => {
const brokerName = trigger?.spec?.broker;
const connectedService = trigger.spec?.subscriber?.ref?.name;
const connectedService = trigger.spec?.subscriber?.ref;
if (name === brokerName && ksservices?.data.length > 0) {
const knativeService = _.find(ksservices.data as K8sResourceKind[], {
metadata: { name: connectedService },
metadata: { name: connectedService.name },
});
if (knativeService) {
if (
knativeService &&
connectedService.apiVersion === apiVersionForReference(referenceFor(knativeService))
) {
const {
metadata: { uid: serviceUid },
} = knativeService;
Expand Down Expand Up @@ -810,7 +839,10 @@ export const getSubscriptionTopologyEdgeItems = (
const {
metadata: { uid: resUid, name: resName },
} = res;
if (resName === svcData.name) {
if (
resName === svcData.name &&
svcData.apiVersion === apiVersionForReference(referenceFor(resource))
) {
edges.push({
id: `${uid}_${resUid}`,
type: EdgeType.EventPubSubLink,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,12 @@ export const getBaseWatchedResources = (namespace: string): WatchK8sResources<an
namespace,
optional: true,
},
services: {
isList: true,
kind: 'Service',
namespace,
optional: true,
},
hpas: {
isList: true,
kind: HorizontalPodAutoscalerModel.kind,
Expand Down

0 comments on commit 275f3d4

Please sign in to comment.