@backstage/plugin-kubernetes-backend 0.0.0-nightly-202191222240 → 0.0.0-nightly-202191722049
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -1
- package/dist/index.cjs.js +137 -69
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +60 -17
- package/package.json +5 -5
package/CHANGELOG.md
CHANGED
|
@@ -1,10 +1,31 @@
|
|
|
1
1
|
# @backstage/plugin-kubernetes-backend
|
|
2
2
|
|
|
3
|
-
## 0.
|
|
3
|
+
## 0.3.17
|
|
4
4
|
|
|
5
5
|
### Patch Changes
|
|
6
6
|
|
|
7
7
|
- 89bcf90b66: Refactor kubernetes fetcher to reduce boilerplate code
|
|
8
|
+
- a982e166c5: Enable customization of services used by the kubernetes backend plugin
|
|
9
|
+
|
|
10
|
+
The createRouter function has been deprecated in favor of a KubernetesBuilder object.
|
|
11
|
+
Here's how you should upgrade your projects when configuring the Kubernetes backend plugin.
|
|
12
|
+
in your `packages/backend/src/plugins/kubernetes.ts` file for instance:
|
|
13
|
+
|
|
14
|
+
```typescript
|
|
15
|
+
import { KubernetesBuilder } from '@backstage/plugin-kubernetes-backend';
|
|
16
|
+
import { PluginEnvironment } from '../types';
|
|
17
|
+
|
|
18
|
+
export default async function createPlugin({
|
|
19
|
+
logger,
|
|
20
|
+
config,
|
|
21
|
+
}: PluginEnvironment) {
|
|
22
|
+
const { router } = await KubernetesBuilder.createBuilder({
|
|
23
|
+
logger,
|
|
24
|
+
config,
|
|
25
|
+
}).build();
|
|
26
|
+
return router;
|
|
27
|
+
}
|
|
28
|
+
```
|
|
8
29
|
|
|
9
30
|
## 0.3.16
|
|
10
31
|
|
package/dist/index.cjs.js
CHANGED
|
@@ -479,81 +479,149 @@ class KubernetesClientBasedFetcher {
|
|
|
479
479
|
}
|
|
480
480
|
}
|
|
481
481
|
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
482
|
+
class KubernetesBuilder {
|
|
483
|
+
constructor(env) {
|
|
484
|
+
this.env = env;
|
|
485
|
+
}
|
|
486
|
+
static createBuilder(env) {
|
|
487
|
+
return new KubernetesBuilder(env);
|
|
488
|
+
}
|
|
489
|
+
async build() {
|
|
490
|
+
var _a, _b, _c, _d;
|
|
491
|
+
const logger = this.env.logger;
|
|
492
|
+
logger.info("Initializing Kubernetes backend");
|
|
493
|
+
const customResources = this.buildCustomResources();
|
|
494
|
+
const fetcher = (_a = this.fetcher) != null ? _a : this.buildFetcher();
|
|
495
|
+
const clusterSupplier = (_b = this.clusterSupplier) != null ? _b : this.buildClusterSupplier();
|
|
496
|
+
const clusterDetails = await this.fetchClusterDetails(clusterSupplier);
|
|
497
|
+
const serviceLocator = (_c = this.serviceLocator) != null ? _c : this.buildServiceLocator(this.getServiceLocatorMethod(), clusterDetails);
|
|
498
|
+
const objectsProvider = (_d = this.objectsProvider) != null ? _d : this.buildObjectsProvider({
|
|
499
|
+
logger,
|
|
500
|
+
fetcher,
|
|
501
|
+
serviceLocator,
|
|
502
|
+
customResources,
|
|
503
|
+
objectTypesToFetch: this.getObjectTypesToFetch()
|
|
504
|
+
});
|
|
505
|
+
const router = this.buildRouter(objectsProvider, clusterDetails);
|
|
506
|
+
return {
|
|
507
|
+
clusterDetails,
|
|
508
|
+
clusterSupplier,
|
|
509
|
+
customResources,
|
|
510
|
+
fetcher,
|
|
511
|
+
objectsProvider,
|
|
512
|
+
router,
|
|
513
|
+
serviceLocator
|
|
514
|
+
};
|
|
491
515
|
}
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
516
|
+
setClusterSupplier(clusterSupplier) {
|
|
517
|
+
this.clusterSupplier = clusterSupplier;
|
|
518
|
+
return this;
|
|
519
|
+
}
|
|
520
|
+
setObjectsProvider(objectsProvider) {
|
|
521
|
+
this.objectsProvider = objectsProvider;
|
|
522
|
+
return this;
|
|
523
|
+
}
|
|
524
|
+
setFetcher(fetcher) {
|
|
525
|
+
this.fetcher = fetcher;
|
|
526
|
+
return this;
|
|
527
|
+
}
|
|
528
|
+
setServiceLocator(serviceLocator) {
|
|
529
|
+
this.serviceLocator = serviceLocator;
|
|
530
|
+
return this;
|
|
531
|
+
}
|
|
532
|
+
buildCustomResources() {
|
|
533
|
+
var _a;
|
|
534
|
+
const customResources = ((_a = this.env.config.getOptionalConfigArray("kubernetes.customResources")) != null ? _a : []).map((c) => ({
|
|
535
|
+
group: c.getString("group"),
|
|
536
|
+
apiVersion: c.getString("apiVersion"),
|
|
537
|
+
plural: c.getString("plural")
|
|
538
|
+
}));
|
|
539
|
+
this.env.logger.info(`action=LoadingCustomResources numOfCustomResources=${customResources.length}`);
|
|
540
|
+
return customResources;
|
|
541
|
+
}
|
|
542
|
+
buildClusterSupplier() {
|
|
543
|
+
const config = this.env.config;
|
|
544
|
+
return {
|
|
545
|
+
getClusters() {
|
|
546
|
+
return getCombinedClusterDetails(config);
|
|
547
|
+
}
|
|
548
|
+
};
|
|
549
|
+
}
|
|
550
|
+
buildObjectsProvider(options) {
|
|
551
|
+
return new KubernetesFanOutHandler(options);
|
|
552
|
+
}
|
|
553
|
+
buildFetcher() {
|
|
554
|
+
return new KubernetesClientBasedFetcher({
|
|
555
|
+
kubernetesClientProvider: new KubernetesClientProvider(),
|
|
556
|
+
logger: this.env.logger
|
|
557
|
+
});
|
|
558
|
+
}
|
|
559
|
+
buildServiceLocator(method, clusterDetails) {
|
|
560
|
+
switch (method) {
|
|
561
|
+
case "multiTenant":
|
|
562
|
+
return this.buildMultiTenantServiceLocator(clusterDetails);
|
|
563
|
+
case "http":
|
|
564
|
+
return this.buildHttpServiceLocator(clusterDetails);
|
|
565
|
+
default:
|
|
566
|
+
throw new Error(`Unsupported kubernetes.clusterLocatorMethod "${method}"`);
|
|
505
567
|
}
|
|
506
|
-
}
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
568
|
+
}
|
|
569
|
+
buildMultiTenantServiceLocator(clusterDetails) {
|
|
570
|
+
return new MultiTenantServiceLocator(clusterDetails);
|
|
571
|
+
}
|
|
572
|
+
buildHttpServiceLocator(_clusterDetails) {
|
|
573
|
+
throw new Error("not implemented");
|
|
574
|
+
}
|
|
575
|
+
buildRouter(objectsProvider, clusterDetails) {
|
|
576
|
+
const logger = this.env.logger;
|
|
577
|
+
const router = Router__default['default']();
|
|
578
|
+
router.use(express__default['default'].json());
|
|
579
|
+
router.post("/services/:serviceId", async (req, res) => {
|
|
580
|
+
const serviceId = req.params.serviceId;
|
|
581
|
+
const requestBody = req.body;
|
|
582
|
+
try {
|
|
583
|
+
const response = await objectsProvider.getKubernetesObjectsByEntity(requestBody);
|
|
584
|
+
res.json(response);
|
|
585
|
+
} catch (e) {
|
|
586
|
+
logger.error(`action=retrieveObjectsByServiceId service=${serviceId}, error=${e}`);
|
|
587
|
+
res.status(500).json({error: e.message});
|
|
588
|
+
}
|
|
514
589
|
});
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
590
|
+
router.get("/clusters", async (_, res) => {
|
|
591
|
+
res.json({
|
|
592
|
+
items: clusterDetails.map((cd) => ({
|
|
593
|
+
name: cd.name,
|
|
594
|
+
dashboardUrl: cd.dashboardUrl,
|
|
595
|
+
authProvider: cd.authProvider
|
|
596
|
+
}))
|
|
597
|
+
});
|
|
598
|
+
});
|
|
599
|
+
return router;
|
|
600
|
+
}
|
|
601
|
+
async fetchClusterDetails(clusterSupplier) {
|
|
602
|
+
const clusterDetails = await clusterSupplier.getClusters();
|
|
603
|
+
this.env.logger.info(`action=loadClusterDetails numOfClustersLoaded=${clusterDetails.length}`);
|
|
604
|
+
return clusterDetails;
|
|
605
|
+
}
|
|
606
|
+
getServiceLocatorMethod() {
|
|
607
|
+
return this.env.config.getString("kubernetes.serviceLocatorMethod.type");
|
|
608
|
+
}
|
|
609
|
+
getObjectTypesToFetch() {
|
|
610
|
+
const objectTypesToFetchStrings = this.env.config.getOptionalStringArray("kubernetes.objectTypes");
|
|
611
|
+
let objectTypesToFetch;
|
|
612
|
+
if (objectTypesToFetchStrings) {
|
|
613
|
+
objectTypesToFetch = DEFAULT_OBJECTS.filter((obj) => objectTypesToFetchStrings.includes(obj.objectType));
|
|
614
|
+
}
|
|
615
|
+
return objectTypesToFetch;
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
|
|
518
619
|
async function createRouter(options) {
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
logger.info("Initializing Kubernetes backend");
|
|
522
|
-
const customResources = ((_a = options.config.getOptionalConfigArray("kubernetes.customResources")) != null ? _a : []).map((c) => ({
|
|
523
|
-
group: c.getString("group"),
|
|
524
|
-
apiVersion: c.getString("apiVersion"),
|
|
525
|
-
plural: c.getString("plural"),
|
|
526
|
-
objectType: "customresources"
|
|
527
|
-
}));
|
|
528
|
-
logger.info(`action=LoadingCustomResources numOfCustomResources=${customResources.length}`);
|
|
529
|
-
const fetcher = new KubernetesClientBasedFetcher({
|
|
530
|
-
kubernetesClientProvider: new KubernetesClientProvider(),
|
|
531
|
-
logger
|
|
532
|
-
});
|
|
533
|
-
let clusterDetails;
|
|
534
|
-
if (options.clusterSupplier) {
|
|
535
|
-
clusterDetails = await options.clusterSupplier.getClusters();
|
|
536
|
-
} else {
|
|
537
|
-
clusterDetails = await getCombinedClusterDetails(options.config);
|
|
538
|
-
}
|
|
539
|
-
logger.info(`action=loadClusterDetails numOfClustersLoaded=${clusterDetails.length}`);
|
|
540
|
-
const serviceLocator = getServiceLocator(options.config, clusterDetails);
|
|
541
|
-
const objectTypesToFetchStrings = options.config.getOptionalStringArray("kubernetes.objectTypes");
|
|
542
|
-
let objectTypesToFetch;
|
|
543
|
-
if (objectTypesToFetchStrings) {
|
|
544
|
-
objectTypesToFetch = DEFAULT_OBJECTS.filter((obj) => objectTypesToFetchStrings.includes(obj.objectType));
|
|
545
|
-
}
|
|
546
|
-
const kubernetesFanOutHandler = new KubernetesFanOutHandler({
|
|
547
|
-
logger,
|
|
548
|
-
fetcher,
|
|
549
|
-
serviceLocator,
|
|
550
|
-
customResources,
|
|
551
|
-
objectTypesToFetch
|
|
552
|
-
});
|
|
553
|
-
return makeRouter(logger, kubernetesFanOutHandler, clusterDetails);
|
|
620
|
+
const {router} = await KubernetesBuilder.createBuilder(options).setClusterSupplier(options.clusterSupplier).build();
|
|
621
|
+
return router;
|
|
554
622
|
}
|
|
555
623
|
|
|
556
624
|
exports.DEFAULT_OBJECTS = DEFAULT_OBJECTS;
|
|
625
|
+
exports.KubernetesBuilder = KubernetesBuilder;
|
|
557
626
|
exports.createRouter = createRouter;
|
|
558
|
-
exports.makeRouter = makeRouter;
|
|
559
627
|
//# sourceMappingURL=index.cjs.js.map
|
package/dist/index.cjs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs.js","sources":["../src/cluster-locator/ConfigClusterLocator.ts","../src/cluster-locator/GkeClusterLocator.ts","../src/cluster-locator/index.ts","../src/service-locator/MultiTenantServiceLocator.ts","../src/service/KubernetesClientProvider.ts","../src/kubernetes-auth-translator/GoogleKubernetesAuthTranslator.ts","../src/kubernetes-auth-translator/ServiceAccountKubernetesAuthTranslator.ts","../src/kubernetes-auth-translator/AwsIamKubernetesAuthTranslator.ts","../src/kubernetes-auth-translator/KubernetesAuthTranslatorGenerator.ts","../src/service/KubernetesFanOutHandler.ts","../src/service/KubernetesFetcher.ts","../src/service/router.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport { ClusterDetails, KubernetesClustersSupplier } from '../types/types';\n\nexport class ConfigClusterLocator implements KubernetesClustersSupplier {\n private readonly clusterDetails: ClusterDetails[];\n\n constructor(clusterDetails: ClusterDetails[]) {\n this.clusterDetails = clusterDetails;\n }\n\n static fromConfig(config: Config): ConfigClusterLocator {\n // TODO: Add validation that authProvider is required and serviceAccountToken\n // is required if authProvider is serviceAccount\n return new ConfigClusterLocator(\n config.getConfigArray('clusters').map(c => {\n const authProvider = c.getString('authProvider');\n const clusterDetails: ClusterDetails = {\n name: c.getString('name'),\n url: c.getString('url'),\n serviceAccountToken: c.getOptionalString('serviceAccountToken'),\n skipTLSVerify: c.getOptionalBoolean('skipTLSVerify') ?? false,\n authProvider: authProvider,\n };\n const dashboardUrl = c.getOptionalString('dashboardUrl');\n if (dashboardUrl) {\n clusterDetails.dashboardUrl = dashboardUrl;\n }\n const dashboardApp = c.getOptionalString('dashboardApp');\n if (dashboardApp) {\n clusterDetails.dashboardApp = dashboardApp;\n }\n\n switch (authProvider) {\n case 'google': {\n return clusterDetails;\n }\n case 'aws': {\n const assumeRole = c.getOptionalString('assumeRole');\n const externalId = c.getOptionalString('externalId');\n\n return { assumeRole, externalId, ...clusterDetails };\n }\n case 'serviceAccount': {\n return clusterDetails;\n }\n default: {\n throw new Error(\n `authProvider \"${authProvider}\" has no config associated with it`,\n );\n }\n }\n }),\n );\n }\n\n async getClusters(): Promise<ClusterDetails[]> {\n return this.clusterDetails;\n }\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport * as container from '@google-cloud/container';\nimport { GKEClusterDetails, KubernetesClustersSupplier } from '../types/types';\n\ntype GkeClusterLocatorOptions = {\n projectId: string;\n region?: string;\n skipTLSVerify?: boolean;\n};\n\nexport class GkeClusterLocator implements KubernetesClustersSupplier {\n constructor(\n private readonly options: GkeClusterLocatorOptions,\n private readonly client: container.v1.ClusterManagerClient,\n ) {}\n\n static fromConfigWithClient(\n config: Config,\n client: container.v1.ClusterManagerClient,\n ): GkeClusterLocator {\n const options = {\n projectId: config.getString('projectId'),\n region: config.getOptionalString('region') ?? '-',\n skipTLSVerify: config.getOptionalBoolean('skipTLSVerify') ?? false,\n };\n return new GkeClusterLocator(options, client);\n }\n\n static fromConfig(config: Config): GkeClusterLocator {\n return GkeClusterLocator.fromConfigWithClient(\n config,\n new container.v1.ClusterManagerClient(),\n );\n }\n\n async getClusters(): Promise<GKEClusterDetails[]> {\n const { projectId, region, skipTLSVerify } = this.options;\n const request = {\n parent: `projects/${projectId}/locations/${region}`,\n };\n\n try {\n const [response] = await this.client.listClusters(request);\n return (response.clusters ?? []).map(r => ({\n // TODO filter out clusters which don't have name or endpoint\n name: r.name ?? 'unknown',\n url: `https://${r.endpoint ?? ''}`,\n authProvider: 'google',\n skipTLSVerify,\n }));\n } catch (e) {\n throw new Error(\n `There was an error retrieving clusters from GKE for projectId=${projectId} region=${region} : [${e.message}]`,\n );\n }\n }\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport { ClusterDetails } from '../types/types';\nimport { ConfigClusterLocator } from './ConfigClusterLocator';\nimport { GkeClusterLocator } from './GkeClusterLocator';\n\nexport const getCombinedClusterDetails = async (\n rootConfig: Config,\n): Promise<ClusterDetails[]> => {\n return Promise.all(\n rootConfig\n .getConfigArray('kubernetes.clusterLocatorMethods')\n .map(clusterLocatorMethod => {\n const type = clusterLocatorMethod.getString('type');\n switch (type) {\n case 'config':\n return ConfigClusterLocator.fromConfig(\n clusterLocatorMethod,\n ).getClusters();\n case 'gke':\n return GkeClusterLocator.fromConfig(\n clusterLocatorMethod,\n ).getClusters();\n default:\n throw new Error(\n `Unsupported kubernetes.clusterLocatorMethods: \"${type}\"`,\n );\n }\n }),\n )\n .then(res => {\n return res.flat();\n })\n .catch(e => {\n throw e;\n });\n};\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ClusterDetails, KubernetesServiceLocator } from '../types/types';\n\n// This locator assumes that every service is located on every cluster\n// Therefore it will always return all clusters provided\nexport class MultiTenantServiceLocator implements KubernetesServiceLocator {\n private readonly clusterDetails: ClusterDetails[];\n\n constructor(clusterDetails: ClusterDetails[]) {\n this.clusterDetails = clusterDetails;\n }\n\n // As this implementation always returns all clusters serviceId is ignored here\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async getClustersByServiceId(_serviceId: string): Promise<ClusterDetails[]> {\n return this.clusterDetails;\n }\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AppsV1Api,\n AutoscalingV1Api,\n CoreV1Api,\n KubeConfig,\n NetworkingV1beta1Api,\n CustomObjectsApi,\n} from '@kubernetes/client-node';\nimport { ClusterDetails } from '../types/types';\n\nexport class KubernetesClientProvider {\n // visible for testing\n getKubeConfig(clusterDetails: ClusterDetails) {\n const cluster = {\n name: clusterDetails.name,\n server: clusterDetails.url,\n skipTLSVerify: clusterDetails.skipTLSVerify,\n };\n\n // TODO configure\n const user = {\n name: 'backstage',\n token: clusterDetails.serviceAccountToken,\n };\n\n const context = {\n name: `${clusterDetails.name}`,\n user: user.name,\n cluster: cluster.name,\n };\n\n const kc = new KubeConfig();\n kc.loadFromOptions({\n clusters: [cluster],\n users: [user],\n contexts: [context],\n currentContext: context.name,\n });\n return kc;\n }\n\n getCoreClientByClusterDetails(clusterDetails: ClusterDetails) {\n const kc = this.getKubeConfig(clusterDetails);\n\n return kc.makeApiClient(CoreV1Api);\n }\n\n getAppsClientByClusterDetails(clusterDetails: ClusterDetails) {\n const kc = this.getKubeConfig(clusterDetails);\n\n return kc.makeApiClient(AppsV1Api);\n }\n\n getAutoscalingClientByClusterDetails(clusterDetails: ClusterDetails) {\n const kc = this.getKubeConfig(clusterDetails);\n\n return kc.makeApiClient(AutoscalingV1Api);\n }\n\n getNetworkingBeta1Client(clusterDetails: ClusterDetails) {\n const kc = this.getKubeConfig(clusterDetails);\n\n return kc.makeApiClient(NetworkingV1beta1Api);\n }\n\n getCustomObjectsClient(clusterDetails: ClusterDetails) {\n const kc = this.getKubeConfig(clusterDetails);\n\n return kc.makeApiClient(CustomObjectsApi);\n }\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { KubernetesAuthTranslator } from './types';\nimport { GKEClusterDetails } from '../types/types';\nimport { KubernetesRequestBody } from '@backstage/plugin-kubernetes-common';\n\nexport class GoogleKubernetesAuthTranslator\n implements KubernetesAuthTranslator\n{\n async decorateClusterDetailsWithAuth(\n clusterDetails: GKEClusterDetails,\n requestBody: KubernetesRequestBody,\n ): Promise<GKEClusterDetails> {\n const clusterDetailsWithAuthToken: GKEClusterDetails = Object.assign(\n {},\n clusterDetails,\n );\n const authToken: string | undefined = requestBody.auth?.google;\n\n if (authToken) {\n clusterDetailsWithAuthToken.serviceAccountToken = authToken;\n } else {\n throw new Error(\n 'Google token not found under auth.google in request body',\n );\n }\n return clusterDetailsWithAuthToken;\n }\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { KubernetesAuthTranslator } from './types';\nimport { ServiceAccountClusterDetails } from '../types/types';\nimport { KubernetesRequestBody } from '@backstage/plugin-kubernetes-common';\n\nexport class ServiceAccountKubernetesAuthTranslator\n implements KubernetesAuthTranslator\n{\n async decorateClusterDetailsWithAuth(\n clusterDetails: ServiceAccountClusterDetails,\n // To ignore TS6133 linting error where it detects 'requestBody' is declared but its value is never read.\n // @ts-ignore-start\n requestBody: KubernetesRequestBody, // eslint-disable-line @typescript-eslint/no-unused-vars\n // @ts-ignore-end\n ): Promise<ServiceAccountClusterDetails> {\n return clusterDetails;\n }\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport AWS, { Credentials } from 'aws-sdk';\nimport { sign } from 'aws4';\nimport { AWSClusterDetails } from '../types/types';\nimport { KubernetesAuthTranslator } from './types';\n\nconst base64 = (str: string) =>\n Buffer.from(str.toString(), 'binary').toString('base64');\nconst prepend = (prep: string) => (str: string) => prep + str;\nconst replace =\n (search: string | RegExp, substitution: string) => (str: string) =>\n str.replace(search, substitution);\nconst pipe =\n (fns: ReadonlyArray<any>) =>\n (thing: string): string =>\n fns.reduce((val, fn) => fn(val), thing);\nconst removePadding = replace(/=+$/, '');\nconst makeUrlSafe = pipe([replace('+', '-'), replace('/', '_')]);\n\ntype SigningCreds = {\n accessKeyId: string | undefined;\n secretAccessKey: string | undefined;\n sessionToken: string | undefined;\n};\n\nexport class AwsIamKubernetesAuthTranslator\n implements KubernetesAuthTranslator\n{\n validCredentials(creds: SigningCreds): boolean {\n return (creds?.accessKeyId &&\n creds?.secretAccessKey &&\n creds?.sessionToken) as unknown as boolean;\n }\n\n awsGetCredentials = async (): Promise<Credentials> => {\n return new Promise((resolve, reject) => {\n AWS.config.getCredentials(err => {\n if (err) {\n return reject(err);\n }\n\n return resolve(AWS.config.credentials as Credentials);\n });\n });\n };\n\n async getCredentials(\n assumeRole?: string,\n externalId?: string,\n ): Promise<SigningCreds> {\n return new Promise<SigningCreds>(async (resolve, reject) => {\n const awsCreds = await this.awsGetCredentials();\n\n if (!(awsCreds instanceof Credentials))\n return reject(Error('No AWS credentials found.'));\n\n let creds: SigningCreds = {\n accessKeyId: awsCreds.accessKeyId,\n secretAccessKey: awsCreds.secretAccessKey,\n sessionToken: awsCreds.sessionToken,\n };\n\n if (!this.validCredentials(creds))\n return reject(Error('Invalid AWS credentials found.'));\n if (!assumeRole) return resolve(creds);\n\n try {\n const params: AWS.STS.Types.AssumeRoleRequest = {\n RoleArn: assumeRole,\n RoleSessionName: 'backstage-login',\n };\n if (externalId) params.ExternalId = externalId;\n\n const assumedRole = await new AWS.STS().assumeRole(params).promise();\n\n if (!assumedRole.Credentials) {\n throw new Error(`No credentials returned for role ${assumeRole}`);\n }\n\n creds = {\n accessKeyId: assumedRole.Credentials.AccessKeyId,\n secretAccessKey: assumedRole.Credentials.SecretAccessKey,\n sessionToken: assumedRole.Credentials.SessionToken,\n };\n } catch (e) {\n console.warn(`There was an error assuming the role: ${e}`);\n return reject(Error(`Unable to assume role: ${e}`));\n }\n return resolve(creds);\n });\n }\n async getBearerToken(\n clusterName: string,\n assumeRole?: string,\n externalId?: string,\n ): Promise<string> {\n const credentials = await this.getCredentials(assumeRole, externalId);\n\n const request = {\n host: `sts.amazonaws.com`,\n path: `/?Action=GetCallerIdentity&Version=2011-06-15&X-Amz-Expires=60`,\n headers: {\n 'x-k8s-aws-id': clusterName,\n },\n signQuery: true,\n };\n\n const signedRequest = sign(request, credentials);\n\n return pipe([\n (signed: any) => `https://${signed.host}${signed.path}`,\n base64,\n removePadding,\n makeUrlSafe,\n prepend('k8s-aws-v1.'),\n ])(signedRequest);\n }\n\n async decorateClusterDetailsWithAuth(\n clusterDetails: AWSClusterDetails,\n ): Promise<AWSClusterDetails> {\n const clusterDetailsWithAuthToken: AWSClusterDetails = Object.assign(\n {},\n clusterDetails,\n );\n\n clusterDetailsWithAuthToken.serviceAccountToken = await this.getBearerToken(\n clusterDetails.name,\n clusterDetails.assumeRole,\n clusterDetails.externalId,\n );\n return clusterDetailsWithAuthToken;\n }\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { KubernetesAuthTranslator } from './types';\nimport { GoogleKubernetesAuthTranslator } from './GoogleKubernetesAuthTranslator';\nimport { ServiceAccountKubernetesAuthTranslator } from './ServiceAccountKubernetesAuthTranslator';\nimport { AwsIamKubernetesAuthTranslator } from './AwsIamKubernetesAuthTranslator';\n\nexport class KubernetesAuthTranslatorGenerator {\n static getKubernetesAuthTranslatorInstance(\n authProvider: string,\n ): KubernetesAuthTranslator {\n switch (authProvider) {\n case 'google': {\n return new GoogleKubernetesAuthTranslator();\n }\n case 'aws': {\n return new AwsIamKubernetesAuthTranslator();\n }\n case 'serviceAccount': {\n return new ServiceAccountKubernetesAuthTranslator();\n }\n default: {\n throw new Error(\n `authProvider \"${authProvider}\" has no KubernetesAuthTranslator associated with it`,\n );\n }\n }\n }\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger } from 'winston';\nimport {\n ClusterDetails,\n CustomResource,\n KubernetesFetcher,\n KubernetesServiceLocator,\n ObjectToFetch,\n} from '../types/types';\nimport {\n ClusterObjects,\n KubernetesRequestBody,\n} from '@backstage/plugin-kubernetes-common';\nimport { KubernetesAuthTranslator } from '../kubernetes-auth-translator/types';\nimport { KubernetesAuthTranslatorGenerator } from '../kubernetes-auth-translator/KubernetesAuthTranslatorGenerator';\n\nexport const DEFAULT_OBJECTS: ObjectToFetch[] = [\n {\n group: '',\n apiVersion: 'v1',\n plural: 'pods',\n objectType: 'pods',\n },\n {\n group: '',\n apiVersion: 'v1',\n plural: 'services',\n objectType: 'services',\n },\n {\n group: '',\n apiVersion: 'v1',\n plural: 'configmaps',\n objectType: 'configmaps',\n },\n {\n group: 'apps',\n apiVersion: 'v1',\n plural: 'deployments',\n objectType: 'deployments',\n },\n {\n group: 'apps',\n apiVersion: 'v1',\n plural: 'replicasets',\n objectType: 'replicasets',\n },\n {\n group: 'autoscaling',\n apiVersion: 'v1',\n plural: 'horizontalpodautoscalers',\n objectType: 'horizontalpodautoscalers',\n },\n {\n group: 'networking.k8s.io',\n apiVersion: 'v1',\n plural: 'ingresses',\n objectType: 'ingresses',\n },\n];\n\nexport interface KubernetesFanOutHandlerOptions {\n logger: Logger;\n fetcher: KubernetesFetcher;\n serviceLocator: KubernetesServiceLocator;\n customResources: CustomResource[];\n objectTypesToFetch?: ObjectToFetch[];\n}\n\nexport class KubernetesFanOutHandler {\n private readonly logger: Logger;\n private readonly fetcher: KubernetesFetcher;\n private readonly serviceLocator: KubernetesServiceLocator;\n private readonly customResources: CustomResource[];\n private readonly objectTypesToFetch: Set<ObjectToFetch>;\n\n constructor({\n logger,\n fetcher,\n serviceLocator,\n customResources,\n objectTypesToFetch = DEFAULT_OBJECTS,\n }: KubernetesFanOutHandlerOptions) {\n this.logger = logger;\n this.fetcher = fetcher;\n this.serviceLocator = serviceLocator;\n this.customResources = customResources;\n this.objectTypesToFetch = new Set(objectTypesToFetch);\n }\n\n async getKubernetesObjectsByEntity(requestBody: KubernetesRequestBody) {\n const entityName =\n requestBody.entity?.metadata?.annotations?.[\n 'backstage.io/kubernetes-id'\n ] || requestBody.entity?.metadata?.name;\n\n const clusterDetails: ClusterDetails[] =\n await this.serviceLocator.getClustersByServiceId(entityName);\n\n // Execute all of these async actions simultaneously/without blocking sequentially as no common object is modified by them\n const promises: Promise<ClusterDetails>[] = clusterDetails.map(cd => {\n const kubernetesAuthTranslator: KubernetesAuthTranslator =\n KubernetesAuthTranslatorGenerator.getKubernetesAuthTranslatorInstance(\n cd.authProvider,\n );\n return kubernetesAuthTranslator.decorateClusterDetailsWithAuth(\n cd,\n requestBody,\n );\n });\n const clusterDetailsDecoratedForAuth: ClusterDetails[] = await Promise.all(\n promises,\n );\n\n this.logger.info(\n `entity.metadata.name=${entityName} clusterDetails=[${clusterDetailsDecoratedForAuth\n .map(c => c.name)\n .join(', ')}]`,\n );\n\n const labelSelector: string =\n requestBody.entity?.metadata?.annotations?.[\n 'backstage.io/kubernetes-label-selector'\n ] || `backstage.io/kubernetes-id=${entityName}`;\n\n return Promise.all(\n clusterDetailsDecoratedForAuth.map(clusterDetailsItem => {\n return this.fetcher\n .fetchObjectsForService({\n serviceId: entityName,\n clusterDetails: clusterDetailsItem,\n objectTypesToFetch: this.objectTypesToFetch,\n labelSelector,\n customResources: this.customResources,\n })\n .then(result => {\n const objects: ClusterObjects = {\n cluster: {\n name: clusterDetailsItem.name,\n },\n resources: result.responses,\n errors: result.errors,\n };\n if (clusterDetailsItem.dashboardUrl) {\n objects.cluster.dashboardUrl = clusterDetailsItem.dashboardUrl;\n }\n if (clusterDetailsItem.dashboardApp) {\n objects.cluster.dashboardApp = clusterDetailsItem.dashboardApp;\n }\n return objects;\n });\n }),\n ).then(r => ({\n items: r.filter(\n item =>\n (item.errors !== undefined && item.errors.length >= 1) ||\n (item.resources !== undefined &&\n item.resources.length >= 1 &&\n item.resources.some(fr => fr.resources.length >= 1)),\n ),\n }));\n }\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AppsV1Api,\n AutoscalingV1Api,\n CoreV1Api,\n NetworkingV1beta1Api,\n} from '@kubernetes/client-node';\nimport lodash, { Dictionary } from 'lodash';\nimport { Logger } from 'winston';\nimport {\n ClusterDetails,\n FetchResponseWrapper,\n KubernetesFetcher,\n KubernetesObjectTypes,\n ObjectFetchParams,\n ObjectToFetch,\n} from '../types/types';\nimport {\n FetchResponse,\n KubernetesFetchError,\n KubernetesErrorTypes,\n} from '@backstage/plugin-kubernetes-common';\nimport { KubernetesClientProvider } from './KubernetesClientProvider';\n\nexport interface Clients {\n core: CoreV1Api;\n apps: AppsV1Api;\n autoscaling: AutoscalingV1Api;\n networkingBeta1: NetworkingV1beta1Api;\n}\n\nexport interface KubernetesClientBasedFetcherOptions {\n kubernetesClientProvider: KubernetesClientProvider;\n logger: Logger;\n}\n\ntype FetchResult = FetchResponse | KubernetesFetchError;\n\nconst isError = (fr: FetchResult): fr is KubernetesFetchError =>\n fr.hasOwnProperty('errorType');\n\nfunction fetchResultsToResponseWrapper(\n results: FetchResult[],\n): FetchResponseWrapper {\n const groupBy: Dictionary<FetchResult[]> = lodash.groupBy(results, value => {\n return isError(value) ? 'errors' : 'responses';\n });\n\n return {\n errors: groupBy.errors ?? [],\n responses: groupBy.responses ?? [],\n } as FetchResponseWrapper; // TODO would be nice to get rid of this 'as'\n}\n\nconst statusCodeToErrorType = (statusCode: number): KubernetesErrorTypes => {\n switch (statusCode) {\n case 400:\n return 'BAD_REQUEST';\n case 401:\n return 'UNAUTHORIZED_ERROR';\n case 500:\n return 'SYSTEM_ERROR';\n default:\n return 'UNKNOWN_ERROR';\n }\n};\n\nexport class KubernetesClientBasedFetcher implements KubernetesFetcher {\n private readonly kubernetesClientProvider: KubernetesClientProvider;\n private readonly logger: Logger;\n\n constructor({\n kubernetesClientProvider,\n logger,\n }: KubernetesClientBasedFetcherOptions) {\n this.kubernetesClientProvider = kubernetesClientProvider;\n this.logger = logger;\n }\n\n fetchObjectsForService(\n params: ObjectFetchParams,\n ): Promise<FetchResponseWrapper> {\n const fetchResults = Array.from(params.objectTypesToFetch)\n .concat(params.customResources)\n .map(toFetch => {\n return this.fetchResource(\n params.clusterDetails,\n toFetch,\n params.labelSelector ||\n `backstage.io/kubernetes-id=${params.serviceId}`,\n toFetch.objectType,\n ).catch(this.captureKubernetesErrorsRethrowOthers.bind(this));\n });\n\n return Promise.all(fetchResults).then(fetchResultsToResponseWrapper);\n }\n\n private captureKubernetesErrorsRethrowOthers(e: any): KubernetesFetchError {\n if (e.response && e.response.statusCode) {\n this.logger.info(\n `statusCode=${e.response.statusCode} for resource ${e.response.request.uri.pathname}`,\n );\n return {\n errorType: statusCodeToErrorType(e.response.statusCode),\n statusCode: e.response.statusCode,\n resourcePath: e.response.request.uri.pathname,\n };\n }\n throw e;\n }\n\n private fetchResource(\n clusterDetails: ClusterDetails,\n resource: ObjectToFetch,\n labelSelector: string,\n objectType: KubernetesObjectTypes,\n ): Promise<FetchResponse> {\n const customObjects =\n this.kubernetesClientProvider.getCustomObjectsClient(clusterDetails);\n\n customObjects.addInterceptor((requestOptions: any) => {\n requestOptions.uri = requestOptions.uri.replace('/apis//v1/', '/api/v1/');\n });\n\n return customObjects\n .listClusterCustomObject(\n resource.group,\n resource.apiVersion,\n resource.plural,\n '',\n '',\n '',\n labelSelector,\n )\n .then(r => {\n return { type: objectType, resources: (r.body as any).items };\n });\n }\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport express from 'express';\nimport Router from 'express-promise-router';\nimport { Logger } from 'winston';\nimport { getCombinedClusterDetails } from '../cluster-locator';\nimport { MultiTenantServiceLocator } from '../service-locator/MultiTenantServiceLocator';\nimport {\n ClusterDetails,\n KubernetesClustersSupplier,\n KubernetesObjectTypes,\n KubernetesServiceLocator,\n ServiceLocatorMethod,\n CustomResource,\n} from '../types/types';\nimport { KubernetesRequestBody } from '@backstage/plugin-kubernetes-common';\nimport { KubernetesClientProvider } from './KubernetesClientProvider';\nimport {\n KubernetesFanOutHandler,\n DEFAULT_OBJECTS,\n} from './KubernetesFanOutHandler';\nimport { KubernetesClientBasedFetcher } from './KubernetesFetcher';\n\nexport interface RouterOptions {\n logger: Logger;\n config: Config;\n clusterSupplier?: KubernetesClustersSupplier;\n}\n\nconst getServiceLocator = (\n config: Config,\n clusterDetails: ClusterDetails[],\n): KubernetesServiceLocator => {\n const serviceLocatorMethod = config.getString(\n 'kubernetes.serviceLocatorMethod.type',\n ) as ServiceLocatorMethod;\n\n switch (serviceLocatorMethod) {\n case 'multiTenant':\n return new MultiTenantServiceLocator(clusterDetails);\n case 'http':\n throw new Error('not implemented');\n default:\n throw new Error(\n `Unsupported kubernetes.clusterLocatorMethod \"${serviceLocatorMethod}\"`,\n );\n }\n};\n\nexport const makeRouter = (\n logger: Logger,\n kubernetesFanOutHandler: KubernetesFanOutHandler,\n clusterDetails: ClusterDetails[],\n): express.Router => {\n const router = Router();\n router.use(express.json());\n\n router.post('/services/:serviceId', async (req, res) => {\n const serviceId = req.params.serviceId;\n const requestBody: KubernetesRequestBody = req.body;\n try {\n const response =\n await kubernetesFanOutHandler.getKubernetesObjectsByEntity(requestBody);\n res.json(response);\n } catch (e) {\n logger.error(\n `action=retrieveObjectsByServiceId service=${serviceId}, error=${e}`,\n );\n res.status(500).json({ error: e.message });\n }\n });\n\n router.get('/clusters', async (_, res) => {\n res.json({\n items: clusterDetails.map(cd => ({\n name: cd.name,\n dashboardUrl: cd.dashboardUrl,\n authProvider: cd.authProvider,\n })),\n });\n });\n return router;\n};\n\nexport async function createRouter(\n options: RouterOptions,\n): Promise<express.Router> {\n const logger = options.logger;\n\n logger.info('Initializing Kubernetes backend');\n\n const customResources: CustomResource[] = (\n options.config.getOptionalConfigArray('kubernetes.customResources') ?? []\n ).map(\n c =>\n ({\n group: c.getString('group'),\n apiVersion: c.getString('apiVersion'),\n plural: c.getString('plural'),\n objectType: 'customresources',\n } as CustomResource),\n );\n\n logger.info(\n `action=LoadingCustomResources numOfCustomResources=${customResources.length}`,\n );\n\n const fetcher = new KubernetesClientBasedFetcher({\n kubernetesClientProvider: new KubernetesClientProvider(),\n logger,\n });\n\n let clusterDetails: ClusterDetails[];\n\n if (options.clusterSupplier) {\n clusterDetails = await options.clusterSupplier.getClusters();\n } else {\n clusterDetails = await getCombinedClusterDetails(options.config);\n }\n\n logger.info(\n `action=loadClusterDetails numOfClustersLoaded=${clusterDetails.length}`,\n );\n\n const serviceLocator = getServiceLocator(options.config, clusterDetails);\n const objectTypesToFetchStrings = options.config.getOptionalStringArray(\n 'kubernetes.objectTypes',\n ) as KubernetesObjectTypes[];\n\n let objectTypesToFetch;\n\n if (objectTypesToFetchStrings) {\n objectTypesToFetch = DEFAULT_OBJECTS.filter(obj =>\n objectTypesToFetchStrings.includes(obj.objectType),\n );\n }\n\n const kubernetesFanOutHandler = new KubernetesFanOutHandler({\n logger,\n fetcher,\n serviceLocator,\n customResources,\n objectTypesToFetch,\n });\n\n return makeRouter(logger, kubernetesFanOutHandler, clusterDetails);\n}\n"],"names":["container","KubeConfig","CoreV1Api","AppsV1Api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,QAAQ;AACxC,QAAI,KAAK;AAAA,MACP,OAAO,eAAe,IAAI;AAAO,QAC/B,MAAM,GAAG;AAAA,QACT,cAAc,GAAG;AAAA,QACjB,cAAc,GAAG;AAAA;AAAA;AAAA;AAIvB,SAAO;AAAA;4BAIP,SACyB;AArG3B;AAsGE,QAAM,SAAS,QAAQ;AAEvB,SAAO,KAAK;AAEZ,QAAM,kBACJ,eAAQ,OAAO,uBAAuB,kCAAtC,YAAuE,IACvE,IACA;AACG,IACC,OAAO,EAAE,UAAU;AAAA,IACnB,YAAY,EAAE,UAAU;AAAA,IACxB,QAAQ,EAAE,UAAU;AAAA,IACpB,YAAY;AAAA;AAIlB,SAAO,KACL,sDAAsD,gBAAgB;AAGxE,QAAM,UAAU,IAAI,6BAA6B;AAAA,IAC/C,0BAA0B,IAAI;AAAA,IAC9B;AAAA;AAGF,MAAI;AAEJ,MAAI,QAAQ,iBAAiB;AAC3B,qBAAiB,MAAM,QAAQ,gBAAgB;AAAA,SAC1C;AACL,qBAAiB,MAAM,0BAA0B,QAAQ;AAAA;AAG3D,SAAO,KACL,iDAAiD,eAAe;AAGlE,QAAM,iBAAiB,kBAAkB,QAAQ,QAAQ;AACzD,QAAM,4BAA4B,QAAQ,OAAO,uBAC/C;AAGF,MAAI;AAEJ,MAAI,2BAA2B;AAC7B,yBAAqB,gBAAgB,OAAO,SAC1C,0BAA0B,SAAS,IAAI;AAAA;AAI3C,QAAM,0BAA0B,IAAI,wBAAwB;AAAA,IAC1D;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA;AAGF,SAAO,WAAW,QAAQ,yBAAyB;AAAA;;;;;;"}
|
|
1
|
+
{"version":3,"file":"index.cjs.js","sources":["../src/cluster-locator/ConfigClusterLocator.ts","../src/cluster-locator/GkeClusterLocator.ts","../src/cluster-locator/index.ts","../src/service-locator/MultiTenantServiceLocator.ts","../src/service/KubernetesClientProvider.ts","../src/kubernetes-auth-translator/GoogleKubernetesAuthTranslator.ts","../src/kubernetes-auth-translator/ServiceAccountKubernetesAuthTranslator.ts","../src/kubernetes-auth-translator/AwsIamKubernetesAuthTranslator.ts","../src/kubernetes-auth-translator/KubernetesAuthTranslatorGenerator.ts","../src/service/KubernetesFanOutHandler.ts","../src/service/KubernetesFetcher.ts","../src/service/KubernetesBuilder.ts","../src/service/router.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport { ClusterDetails, KubernetesClustersSupplier } from '../types/types';\n\nexport class ConfigClusterLocator implements KubernetesClustersSupplier {\n private readonly clusterDetails: ClusterDetails[];\n\n constructor(clusterDetails: ClusterDetails[]) {\n this.clusterDetails = clusterDetails;\n }\n\n static fromConfig(config: Config): ConfigClusterLocator {\n // TODO: Add validation that authProvider is required and serviceAccountToken\n // is required if authProvider is serviceAccount\n return new ConfigClusterLocator(\n config.getConfigArray('clusters').map(c => {\n const authProvider = c.getString('authProvider');\n const clusterDetails: ClusterDetails = {\n name: c.getString('name'),\n url: c.getString('url'),\n serviceAccountToken: c.getOptionalString('serviceAccountToken'),\n skipTLSVerify: c.getOptionalBoolean('skipTLSVerify') ?? false,\n authProvider: authProvider,\n };\n const dashboardUrl = c.getOptionalString('dashboardUrl');\n if (dashboardUrl) {\n clusterDetails.dashboardUrl = dashboardUrl;\n }\n const dashboardApp = c.getOptionalString('dashboardApp');\n if (dashboardApp) {\n clusterDetails.dashboardApp = dashboardApp;\n }\n\n switch (authProvider) {\n case 'google': {\n return clusterDetails;\n }\n case 'aws': {\n const assumeRole = c.getOptionalString('assumeRole');\n const externalId = c.getOptionalString('externalId');\n\n return { assumeRole, externalId, ...clusterDetails };\n }\n case 'serviceAccount': {\n return clusterDetails;\n }\n default: {\n throw new Error(\n `authProvider \"${authProvider}\" has no config associated with it`,\n );\n }\n }\n }),\n );\n }\n\n async getClusters(): Promise<ClusterDetails[]> {\n return this.clusterDetails;\n }\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport * as container from '@google-cloud/container';\nimport { GKEClusterDetails, KubernetesClustersSupplier } from '../types/types';\n\ntype GkeClusterLocatorOptions = {\n projectId: string;\n region?: string;\n skipTLSVerify?: boolean;\n};\n\nexport class GkeClusterLocator implements KubernetesClustersSupplier {\n constructor(\n private readonly options: GkeClusterLocatorOptions,\n private readonly client: container.v1.ClusterManagerClient,\n ) {}\n\n static fromConfigWithClient(\n config: Config,\n client: container.v1.ClusterManagerClient,\n ): GkeClusterLocator {\n const options = {\n projectId: config.getString('projectId'),\n region: config.getOptionalString('region') ?? '-',\n skipTLSVerify: config.getOptionalBoolean('skipTLSVerify') ?? false,\n };\n return new GkeClusterLocator(options, client);\n }\n\n static fromConfig(config: Config): GkeClusterLocator {\n return GkeClusterLocator.fromConfigWithClient(\n config,\n new container.v1.ClusterManagerClient(),\n );\n }\n\n async getClusters(): Promise<GKEClusterDetails[]> {\n const { projectId, region, skipTLSVerify } = this.options;\n const request = {\n parent: `projects/${projectId}/locations/${region}`,\n };\n\n try {\n const [response] = await this.client.listClusters(request);\n return (response.clusters ?? []).map(r => ({\n // TODO filter out clusters which don't have name or endpoint\n name: r.name ?? 'unknown',\n url: `https://${r.endpoint ?? ''}`,\n authProvider: 'google',\n skipTLSVerify,\n }));\n } catch (e) {\n throw new Error(\n `There was an error retrieving clusters from GKE for projectId=${projectId} region=${region} : [${e.message}]`,\n );\n }\n }\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport { ClusterDetails } from '../types/types';\nimport { ConfigClusterLocator } from './ConfigClusterLocator';\nimport { GkeClusterLocator } from './GkeClusterLocator';\n\nexport const getCombinedClusterDetails = async (\n rootConfig: Config,\n): Promise<ClusterDetails[]> => {\n return Promise.all(\n rootConfig\n .getConfigArray('kubernetes.clusterLocatorMethods')\n .map(clusterLocatorMethod => {\n const type = clusterLocatorMethod.getString('type');\n switch (type) {\n case 'config':\n return ConfigClusterLocator.fromConfig(\n clusterLocatorMethod,\n ).getClusters();\n case 'gke':\n return GkeClusterLocator.fromConfig(\n clusterLocatorMethod,\n ).getClusters();\n default:\n throw new Error(\n `Unsupported kubernetes.clusterLocatorMethods: \"${type}\"`,\n );\n }\n }),\n )\n .then(res => {\n return res.flat();\n })\n .catch(e => {\n throw e;\n });\n};\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ClusterDetails, KubernetesServiceLocator } from '../types/types';\n\n// This locator assumes that every service is located on every cluster\n// Therefore it will always return all clusters provided\nexport class MultiTenantServiceLocator implements KubernetesServiceLocator {\n private readonly clusterDetails: ClusterDetails[];\n\n constructor(clusterDetails: ClusterDetails[]) {\n this.clusterDetails = clusterDetails;\n }\n\n // As this implementation always returns all clusters serviceId is ignored here\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async getClustersByServiceId(_serviceId: string): Promise<ClusterDetails[]> {\n return this.clusterDetails;\n }\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AppsV1Api,\n AutoscalingV1Api,\n CoreV1Api,\n KubeConfig,\n NetworkingV1beta1Api,\n CustomObjectsApi,\n} from '@kubernetes/client-node';\nimport { ClusterDetails } from '../types/types';\n\nexport class KubernetesClientProvider {\n // visible for testing\n getKubeConfig(clusterDetails: ClusterDetails) {\n const cluster = {\n name: clusterDetails.name,\n server: clusterDetails.url,\n skipTLSVerify: clusterDetails.skipTLSVerify,\n };\n\n // TODO configure\n const user = {\n name: 'backstage',\n token: clusterDetails.serviceAccountToken,\n };\n\n const context = {\n name: `${clusterDetails.name}`,\n user: user.name,\n cluster: cluster.name,\n };\n\n const kc = new KubeConfig();\n kc.loadFromOptions({\n clusters: [cluster],\n users: [user],\n contexts: [context],\n currentContext: context.name,\n });\n return kc;\n }\n\n getCoreClientByClusterDetails(clusterDetails: ClusterDetails) {\n const kc = this.getKubeConfig(clusterDetails);\n\n return kc.makeApiClient(CoreV1Api);\n }\n\n getAppsClientByClusterDetails(clusterDetails: ClusterDetails) {\n const kc = this.getKubeConfig(clusterDetails);\n\n return kc.makeApiClient(AppsV1Api);\n }\n\n getAutoscalingClientByClusterDetails(clusterDetails: ClusterDetails) {\n const kc = this.getKubeConfig(clusterDetails);\n\n return kc.makeApiClient(AutoscalingV1Api);\n }\n\n getNetworkingBeta1Client(clusterDetails: ClusterDetails) {\n const kc = this.getKubeConfig(clusterDetails);\n\n return kc.makeApiClient(NetworkingV1beta1Api);\n }\n\n getCustomObjectsClient(clusterDetails: ClusterDetails) {\n const kc = this.getKubeConfig(clusterDetails);\n\n return kc.makeApiClient(CustomObjectsApi);\n }\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { KubernetesAuthTranslator } from './types';\nimport { GKEClusterDetails } from '../types/types';\nimport { KubernetesRequestBody } from '@backstage/plugin-kubernetes-common';\n\nexport class GoogleKubernetesAuthTranslator\n implements KubernetesAuthTranslator\n{\n async decorateClusterDetailsWithAuth(\n clusterDetails: GKEClusterDetails,\n requestBody: KubernetesRequestBody,\n ): Promise<GKEClusterDetails> {\n const clusterDetailsWithAuthToken: GKEClusterDetails = Object.assign(\n {},\n clusterDetails,\n );\n const authToken: string | undefined = requestBody.auth?.google;\n\n if (authToken) {\n clusterDetailsWithAuthToken.serviceAccountToken = authToken;\n } else {\n throw new Error(\n 'Google token not found under auth.google in request body',\n );\n }\n return clusterDetailsWithAuthToken;\n }\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { KubernetesAuthTranslator } from './types';\nimport { ServiceAccountClusterDetails } from '../types/types';\nimport { KubernetesRequestBody } from '@backstage/plugin-kubernetes-common';\n\nexport class ServiceAccountKubernetesAuthTranslator\n implements KubernetesAuthTranslator\n{\n async decorateClusterDetailsWithAuth(\n clusterDetails: ServiceAccountClusterDetails,\n // To ignore TS6133 linting error where it detects 'requestBody' is declared but its value is never read.\n // @ts-ignore-start\n requestBody: KubernetesRequestBody, // eslint-disable-line @typescript-eslint/no-unused-vars\n // @ts-ignore-end\n ): Promise<ServiceAccountClusterDetails> {\n return clusterDetails;\n }\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport AWS, { Credentials } from 'aws-sdk';\nimport { sign } from 'aws4';\nimport { AWSClusterDetails } from '../types/types';\nimport { KubernetesAuthTranslator } from './types';\n\nconst base64 = (str: string) =>\n Buffer.from(str.toString(), 'binary').toString('base64');\nconst prepend = (prep: string) => (str: string) => prep + str;\nconst replace =\n (search: string | RegExp, substitution: string) => (str: string) =>\n str.replace(search, substitution);\nconst pipe =\n (fns: ReadonlyArray<any>) =>\n (thing: string): string =>\n fns.reduce((val, fn) => fn(val), thing);\nconst removePadding = replace(/=+$/, '');\nconst makeUrlSafe = pipe([replace('+', '-'), replace('/', '_')]);\n\ntype SigningCreds = {\n accessKeyId: string | undefined;\n secretAccessKey: string | undefined;\n sessionToken: string | undefined;\n};\n\nexport class AwsIamKubernetesAuthTranslator\n implements KubernetesAuthTranslator\n{\n validCredentials(creds: SigningCreds): boolean {\n return (creds?.accessKeyId &&\n creds?.secretAccessKey &&\n creds?.sessionToken) as unknown as boolean;\n }\n\n awsGetCredentials = async (): Promise<Credentials> => {\n return new Promise((resolve, reject) => {\n AWS.config.getCredentials(err => {\n if (err) {\n return reject(err);\n }\n\n return resolve(AWS.config.credentials as Credentials);\n });\n });\n };\n\n async getCredentials(\n assumeRole?: string,\n externalId?: string,\n ): Promise<SigningCreds> {\n return new Promise<SigningCreds>(async (resolve, reject) => {\n const awsCreds = await this.awsGetCredentials();\n\n if (!(awsCreds instanceof Credentials))\n return reject(Error('No AWS credentials found.'));\n\n let creds: SigningCreds = {\n accessKeyId: awsCreds.accessKeyId,\n secretAccessKey: awsCreds.secretAccessKey,\n sessionToken: awsCreds.sessionToken,\n };\n\n if (!this.validCredentials(creds))\n return reject(Error('Invalid AWS credentials found.'));\n if (!assumeRole) return resolve(creds);\n\n try {\n const params: AWS.STS.Types.AssumeRoleRequest = {\n RoleArn: assumeRole,\n RoleSessionName: 'backstage-login',\n };\n if (externalId) params.ExternalId = externalId;\n\n const assumedRole = await new AWS.STS().assumeRole(params).promise();\n\n if (!assumedRole.Credentials) {\n throw new Error(`No credentials returned for role ${assumeRole}`);\n }\n\n creds = {\n accessKeyId: assumedRole.Credentials.AccessKeyId,\n secretAccessKey: assumedRole.Credentials.SecretAccessKey,\n sessionToken: assumedRole.Credentials.SessionToken,\n };\n } catch (e) {\n console.warn(`There was an error assuming the role: ${e}`);\n return reject(Error(`Unable to assume role: ${e}`));\n }\n return resolve(creds);\n });\n }\n async getBearerToken(\n clusterName: string,\n assumeRole?: string,\n externalId?: string,\n ): Promise<string> {\n const credentials = await this.getCredentials(assumeRole, externalId);\n\n const request = {\n host: `sts.amazonaws.com`,\n path: `/?Action=GetCallerIdentity&Version=2011-06-15&X-Amz-Expires=60`,\n headers: {\n 'x-k8s-aws-id': clusterName,\n },\n signQuery: true,\n };\n\n const signedRequest = sign(request, credentials);\n\n return pipe([\n (signed: any) => `https://${signed.host}${signed.path}`,\n base64,\n removePadding,\n makeUrlSafe,\n prepend('k8s-aws-v1.'),\n ])(signedRequest);\n }\n\n async decorateClusterDetailsWithAuth(\n clusterDetails: AWSClusterDetails,\n ): Promise<AWSClusterDetails> {\n const clusterDetailsWithAuthToken: AWSClusterDetails = Object.assign(\n {},\n clusterDetails,\n );\n\n clusterDetailsWithAuthToken.serviceAccountToken = await this.getBearerToken(\n clusterDetails.name,\n clusterDetails.assumeRole,\n clusterDetails.externalId,\n );\n return clusterDetailsWithAuthToken;\n }\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { KubernetesAuthTranslator } from './types';\nimport { GoogleKubernetesAuthTranslator } from './GoogleKubernetesAuthTranslator';\nimport { ServiceAccountKubernetesAuthTranslator } from './ServiceAccountKubernetesAuthTranslator';\nimport { AwsIamKubernetesAuthTranslator } from './AwsIamKubernetesAuthTranslator';\n\nexport class KubernetesAuthTranslatorGenerator {\n static getKubernetesAuthTranslatorInstance(\n authProvider: string,\n ): KubernetesAuthTranslator {\n switch (authProvider) {\n case 'google': {\n return new GoogleKubernetesAuthTranslator();\n }\n case 'aws': {\n return new AwsIamKubernetesAuthTranslator();\n }\n case 'serviceAccount': {\n return new ServiceAccountKubernetesAuthTranslator();\n }\n default: {\n throw new Error(\n `authProvider \"${authProvider}\" has no KubernetesAuthTranslator associated with it`,\n );\n }\n }\n }\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger } from 'winston';\nimport {\n ClusterDetails,\n CustomResource,\n KubernetesFetcher,\n KubernetesObjectsProviderOptions,\n KubernetesServiceLocator,\n ObjectsByEntityRequest,\n ObjectToFetch,\n} from '../types/types';\nimport { KubernetesAuthTranslator } from '../kubernetes-auth-translator/types';\nimport { KubernetesAuthTranslatorGenerator } from '../kubernetes-auth-translator/KubernetesAuthTranslatorGenerator';\nimport {\n ClusterObjects,\n ObjectsByEntityResponse,\n} from '@backstage/plugin-kubernetes-common';\n\nexport const DEFAULT_OBJECTS: ObjectToFetch[] = [\n {\n group: '',\n apiVersion: 'v1',\n plural: 'pods',\n objectType: 'pods',\n },\n {\n group: '',\n apiVersion: 'v1',\n plural: 'services',\n objectType: 'services',\n },\n {\n group: '',\n apiVersion: 'v1',\n plural: 'configmaps',\n objectType: 'configmaps',\n },\n {\n group: 'apps',\n apiVersion: 'v1',\n plural: 'deployments',\n objectType: 'deployments',\n },\n {\n group: 'apps',\n apiVersion: 'v1',\n plural: 'replicasets',\n objectType: 'replicasets',\n },\n {\n group: 'autoscaling',\n apiVersion: 'v1',\n plural: 'horizontalpodautoscalers',\n objectType: 'horizontalpodautoscalers',\n },\n {\n group: 'networking.k8s.io',\n apiVersion: 'v1',\n plural: 'ingresses',\n objectType: 'ingresses',\n },\n];\n\nexport interface KubernetesFanOutHandlerOptions\n extends KubernetesObjectsProviderOptions {}\n\nexport interface KubernetesRequestBody extends ObjectsByEntityRequest {}\n\nexport class KubernetesFanOutHandler {\n private readonly logger: Logger;\n private readonly fetcher: KubernetesFetcher;\n private readonly serviceLocator: KubernetesServiceLocator;\n private readonly customResources: CustomResource[];\n private readonly objectTypesToFetch: Set<ObjectToFetch>;\n\n constructor({\n logger,\n fetcher,\n serviceLocator,\n customResources,\n objectTypesToFetch = DEFAULT_OBJECTS,\n }: KubernetesFanOutHandlerOptions) {\n this.logger = logger;\n this.fetcher = fetcher;\n this.serviceLocator = serviceLocator;\n this.customResources = customResources;\n this.objectTypesToFetch = new Set(objectTypesToFetch);\n }\n\n async getKubernetesObjectsByEntity(\n requestBody: KubernetesRequestBody,\n ): Promise<ObjectsByEntityResponse> {\n const entityName =\n requestBody.entity?.metadata?.annotations?.[\n 'backstage.io/kubernetes-id'\n ] || requestBody.entity?.metadata?.name;\n\n const clusterDetails: ClusterDetails[] =\n await this.serviceLocator.getClustersByServiceId(entityName);\n\n // Execute all of these async actions simultaneously/without blocking sequentially as no common object is modified by them\n const promises: Promise<ClusterDetails>[] = clusterDetails.map(cd => {\n const kubernetesAuthTranslator: KubernetesAuthTranslator =\n KubernetesAuthTranslatorGenerator.getKubernetesAuthTranslatorInstance(\n cd.authProvider,\n );\n return kubernetesAuthTranslator.decorateClusterDetailsWithAuth(\n cd,\n requestBody,\n );\n });\n const clusterDetailsDecoratedForAuth: ClusterDetails[] = await Promise.all(\n promises,\n );\n\n this.logger.info(\n `entity.metadata.name=${entityName} clusterDetails=[${clusterDetailsDecoratedForAuth\n .map(c => c.name)\n .join(', ')}]`,\n );\n\n const labelSelector: string =\n requestBody.entity?.metadata?.annotations?.[\n 'backstage.io/kubernetes-label-selector'\n ] || `backstage.io/kubernetes-id=${entityName}`;\n\n return Promise.all(\n clusterDetailsDecoratedForAuth.map(clusterDetailsItem => {\n return this.fetcher\n .fetchObjectsForService({\n serviceId: entityName,\n clusterDetails: clusterDetailsItem,\n objectTypesToFetch: this.objectTypesToFetch,\n labelSelector,\n customResources: this.customResources,\n })\n .then(result => {\n const objects: ClusterObjects = {\n cluster: {\n name: clusterDetailsItem.name,\n },\n resources: result.responses,\n errors: result.errors,\n };\n if (clusterDetailsItem.dashboardUrl) {\n objects.cluster.dashboardUrl = clusterDetailsItem.dashboardUrl;\n }\n if (clusterDetailsItem.dashboardApp) {\n objects.cluster.dashboardApp = clusterDetailsItem.dashboardApp;\n }\n return objects;\n });\n }),\n ).then(r => ({\n items: r.filter(\n item =>\n (item.errors !== undefined && item.errors.length >= 1) ||\n (item.resources !== undefined &&\n item.resources.length >= 1 &&\n item.resources.some(fr => fr.resources.length >= 1)),\n ),\n }));\n }\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AppsV1Api,\n AutoscalingV1Api,\n CoreV1Api,\n NetworkingV1beta1Api,\n} from '@kubernetes/client-node';\nimport lodash, { Dictionary } from 'lodash';\nimport { Logger } from 'winston';\nimport {\n ClusterDetails,\n FetchResponseWrapper,\n KubernetesFetcher,\n KubernetesObjectTypes,\n ObjectFetchParams,\n ObjectToFetch,\n} from '../types/types';\nimport {\n FetchResponse,\n KubernetesFetchError,\n KubernetesErrorTypes,\n} from '@backstage/plugin-kubernetes-common';\nimport { KubernetesClientProvider } from './KubernetesClientProvider';\n\nexport interface Clients {\n core: CoreV1Api;\n apps: AppsV1Api;\n autoscaling: AutoscalingV1Api;\n networkingBeta1: NetworkingV1beta1Api;\n}\n\nexport interface KubernetesClientBasedFetcherOptions {\n kubernetesClientProvider: KubernetesClientProvider;\n logger: Logger;\n}\n\ntype FetchResult = FetchResponse | KubernetesFetchError;\n\nconst isError = (fr: FetchResult): fr is KubernetesFetchError =>\n fr.hasOwnProperty('errorType');\n\nfunction fetchResultsToResponseWrapper(\n results: FetchResult[],\n): FetchResponseWrapper {\n const groupBy: Dictionary<FetchResult[]> = lodash.groupBy(results, value => {\n return isError(value) ? 'errors' : 'responses';\n });\n\n return {\n errors: groupBy.errors ?? [],\n responses: groupBy.responses ?? [],\n } as FetchResponseWrapper; // TODO would be nice to get rid of this 'as'\n}\n\nconst statusCodeToErrorType = (statusCode: number): KubernetesErrorTypes => {\n switch (statusCode) {\n case 400:\n return 'BAD_REQUEST';\n case 401:\n return 'UNAUTHORIZED_ERROR';\n case 500:\n return 'SYSTEM_ERROR';\n default:\n return 'UNKNOWN_ERROR';\n }\n};\n\nexport class KubernetesClientBasedFetcher implements KubernetesFetcher {\n private readonly kubernetesClientProvider: KubernetesClientProvider;\n private readonly logger: Logger;\n\n constructor({\n kubernetesClientProvider,\n logger,\n }: KubernetesClientBasedFetcherOptions) {\n this.kubernetesClientProvider = kubernetesClientProvider;\n this.logger = logger;\n }\n\n fetchObjectsForService(\n params: ObjectFetchParams,\n ): Promise<FetchResponseWrapper> {\n const fetchResults = Array.from(params.objectTypesToFetch)\n .concat(params.customResources)\n .map(toFetch => {\n return this.fetchResource(\n params.clusterDetails,\n toFetch,\n params.labelSelector ||\n `backstage.io/kubernetes-id=${params.serviceId}`,\n toFetch.objectType,\n ).catch(this.captureKubernetesErrorsRethrowOthers.bind(this));\n });\n\n return Promise.all(fetchResults).then(fetchResultsToResponseWrapper);\n }\n\n private captureKubernetesErrorsRethrowOthers(e: any): KubernetesFetchError {\n if (e.response && e.response.statusCode) {\n this.logger.info(\n `statusCode=${e.response.statusCode} for resource ${e.response.request.uri.pathname}`,\n );\n return {\n errorType: statusCodeToErrorType(e.response.statusCode),\n statusCode: e.response.statusCode,\n resourcePath: e.response.request.uri.pathname,\n };\n }\n throw e;\n }\n\n private fetchResource(\n clusterDetails: ClusterDetails,\n resource: ObjectToFetch,\n labelSelector: string,\n objectType: KubernetesObjectTypes,\n ): Promise<FetchResponse> {\n const customObjects =\n this.kubernetesClientProvider.getCustomObjectsClient(clusterDetails);\n\n customObjects.addInterceptor((requestOptions: any) => {\n requestOptions.uri = requestOptions.uri.replace('/apis//v1/', '/api/v1/');\n });\n\n return customObjects\n .listClusterCustomObject(\n resource.group,\n resource.apiVersion,\n resource.plural,\n '',\n '',\n '',\n labelSelector,\n )\n .then(r => {\n return { type: objectType, resources: (r.body as any).items };\n });\n }\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Config } from '@backstage/config';\nimport express from 'express';\nimport Router from 'express-promise-router';\nimport { Logger } from 'winston';\nimport { getCombinedClusterDetails } from '../cluster-locator';\nimport { MultiTenantServiceLocator } from '../service-locator/MultiTenantServiceLocator';\nimport {\n ClusterDetails,\n KubernetesObjectTypes,\n ServiceLocatorMethod,\n CustomResource,\n KubernetesObjectsProvider,\n ObjectsByEntityRequest,\n KubernetesClustersSupplier,\n KubernetesFetcher,\n KubernetesServiceLocator,\n KubernetesObjectsProviderOptions,\n} from '../types/types';\nimport { KubernetesClientProvider } from './KubernetesClientProvider';\nimport {\n DEFAULT_OBJECTS,\n KubernetesFanOutHandler,\n} from './KubernetesFanOutHandler';\nimport { KubernetesClientBasedFetcher } from './KubernetesFetcher';\n\nexport interface KubernetesEnvironment {\n logger: Logger;\n config: Config;\n}\n\nexport class KubernetesBuilder {\n private clusterSupplier?: KubernetesClustersSupplier;\n private objectsProvider?: KubernetesObjectsProvider;\n private fetcher?: KubernetesFetcher;\n private serviceLocator?: KubernetesServiceLocator;\n\n static createBuilder(env: KubernetesEnvironment) {\n return new KubernetesBuilder(env);\n }\n\n constructor(protected readonly env: KubernetesEnvironment) {}\n\n public async build() {\n const logger = this.env.logger;\n\n logger.info('Initializing Kubernetes backend');\n\n const customResources = this.buildCustomResources();\n\n const fetcher = this.fetcher ?? this.buildFetcher();\n\n const clusterSupplier = this.clusterSupplier ?? this.buildClusterSupplier();\n\n const clusterDetails = await this.fetchClusterDetails(clusterSupplier);\n\n const serviceLocator =\n this.serviceLocator ??\n this.buildServiceLocator(this.getServiceLocatorMethod(), clusterDetails);\n\n const objectsProvider =\n this.objectsProvider ??\n this.buildObjectsProvider({\n logger,\n fetcher,\n serviceLocator,\n customResources,\n objectTypesToFetch: this.getObjectTypesToFetch(),\n });\n\n const router = this.buildRouter(objectsProvider, clusterDetails);\n\n return {\n clusterDetails,\n clusterSupplier,\n customResources,\n fetcher,\n objectsProvider,\n router,\n serviceLocator,\n };\n }\n\n public setClusterSupplier(clusterSupplier?: KubernetesClustersSupplier) {\n this.clusterSupplier = clusterSupplier;\n return this;\n }\n\n public setObjectsProvider(objectsProvider?: KubernetesObjectsProvider) {\n this.objectsProvider = objectsProvider;\n return this;\n }\n\n public setFetcher(fetcher?: KubernetesFetcher) {\n this.fetcher = fetcher;\n return this;\n }\n\n public setServiceLocator(serviceLocator?: KubernetesServiceLocator) {\n this.serviceLocator = serviceLocator;\n return this;\n }\n\n protected buildCustomResources() {\n const customResources: CustomResource[] = (\n this.env.config.getOptionalConfigArray('kubernetes.customResources') ?? []\n ).map(\n c =>\n ({\n group: c.getString('group'),\n apiVersion: c.getString('apiVersion'),\n plural: c.getString('plural'),\n } as CustomResource),\n );\n\n this.env.logger.info(\n `action=LoadingCustomResources numOfCustomResources=${customResources.length}`,\n );\n return customResources;\n }\n\n protected buildClusterSupplier(): KubernetesClustersSupplier {\n const config = this.env.config;\n return {\n getClusters() {\n return getCombinedClusterDetails(config);\n },\n };\n }\n\n protected buildObjectsProvider(\n options: KubernetesObjectsProviderOptions,\n ): KubernetesObjectsProvider {\n return new KubernetesFanOutHandler(options);\n }\n\n protected buildFetcher(): KubernetesFetcher {\n return new KubernetesClientBasedFetcher({\n kubernetesClientProvider: new KubernetesClientProvider(),\n logger: this.env.logger,\n });\n }\n\n protected buildServiceLocator(\n method: ServiceLocatorMethod,\n clusterDetails: ClusterDetails[],\n ): KubernetesServiceLocator {\n switch (method) {\n case 'multiTenant':\n return this.buildMultiTenantServiceLocator(clusterDetails);\n case 'http':\n return this.buildHttpServiceLocator(clusterDetails);\n default:\n throw new Error(\n `Unsupported kubernetes.clusterLocatorMethod \"${method}\"`,\n );\n }\n }\n\n protected buildMultiTenantServiceLocator(\n clusterDetails: ClusterDetails[],\n ): KubernetesServiceLocator {\n return new MultiTenantServiceLocator(clusterDetails);\n }\n\n protected buildHttpServiceLocator(\n _clusterDetails: ClusterDetails[],\n ): KubernetesServiceLocator {\n throw new Error('not implemented');\n }\n\n protected buildRouter(\n objectsProvider: KubernetesObjectsProvider,\n clusterDetails: ClusterDetails[],\n ): express.Router {\n const logger = this.env.logger;\n const router = Router();\n router.use(express.json());\n\n router.post('/services/:serviceId', async (req, res) => {\n const serviceId = req.params.serviceId;\n const requestBody: ObjectsByEntityRequest = req.body;\n try {\n const response = await objectsProvider.getKubernetesObjectsByEntity(\n requestBody,\n );\n res.json(response);\n } catch (e) {\n logger.error(\n `action=retrieveObjectsByServiceId service=${serviceId}, error=${e}`,\n );\n res.status(500).json({ error: e.message });\n }\n });\n\n router.get('/clusters', async (_, res) => {\n res.json({\n items: clusterDetails.map(cd => ({\n name: cd.name,\n dashboardUrl: cd.dashboardUrl,\n authProvider: cd.authProvider,\n })),\n });\n });\n return router;\n }\n\n protected async fetchClusterDetails(\n clusterSupplier: KubernetesClustersSupplier,\n ) {\n const clusterDetails = await clusterSupplier.getClusters();\n\n this.env.logger.info(\n `action=loadClusterDetails numOfClustersLoaded=${clusterDetails.length}`,\n );\n\n return clusterDetails;\n }\n\n protected getServiceLocatorMethod() {\n return this.env.config.getString(\n 'kubernetes.serviceLocatorMethod.type',\n ) as ServiceLocatorMethod;\n }\n\n protected getObjectTypesToFetch() {\n const objectTypesToFetchStrings = this.env.config.getOptionalStringArray(\n 'kubernetes.objectTypes',\n ) as KubernetesObjectTypes[];\n\n let objectTypesToFetch;\n\n if (objectTypesToFetchStrings) {\n objectTypesToFetch = DEFAULT_OBJECTS.filter(obj =>\n objectTypesToFetchStrings.includes(obj.objectType),\n );\n }\n return objectTypesToFetch;\n }\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport { Logger } from 'winston';\nimport { KubernetesClustersSupplier } from '../types/types';\nimport express from 'express';\nimport { KubernetesBuilder } from './KubernetesBuilder';\n\nexport interface RouterOptions {\n logger: Logger;\n config: Config;\n clusterSupplier?: KubernetesClustersSupplier;\n}\n\n/**\n * creates and configure a new router for handling the kubernetes backend APIs\n * @param options - specifies the options required by this plugin\n * @returns a new router\n * @deprecated Please use the new KubernetesBuilder instead like this\n * ```\n * import { KubernetesBuilder } from '@backstage/plugin-kubernetes-backend';\n * const { router } = await KubernetesBuilder.createBuilder({\n * logger,\n * config,\n * }).build();\n * ```\n */\nexport async function createRouter(\n options: RouterOptions,\n): Promise<express.Router> {\n const { router } = await KubernetesBuilder.createBuilder(options)\n .setClusterSupplier(options.clusterSupplier)\n .build();\n return router;\n}\n"],"names":["container","KubeConfig","CoreV1Api","AppsV1Api","AutoscalingV1Api","NetworkingV1beta1Api","CustomObjectsApi","AWS","Credentials","sign","lodash","Router","express"],"m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,wBAAwB,OAAO,KAAK,QAAQ;AACtD,YAAM,YAAY,IAAI,OAAO;AAC7B,YAAM,cAAsC,IAAI;AAChD,UAAI;AACF,cAAM,WAAW,MAAM,gBAAgB,6BACrC;AAEF,YAAI,KAAK;AAAA,eACF,GAAP;AACA,eAAO,MACL,6CAA6C,oBAAoB;AAEnE,YAAI,OAAO,KAAK,KAAK,CAAE,OAAO,EAAE;AAAA;AAAA;AAIpC,WAAO,IAAI,aAAa,OAAO,GAAG,QAAQ;AACxC,UAAI,KAAK;AAAA,QACP,OAAO,eAAe,IAAI;AAAO,UAC/B,MAAM,GAAG;AAAA,UACT,cAAc,GAAG;AAAA,UACjB,cAAc,GAAG;AAAA;AAAA;AAAA;AAIvB,WAAO;AAAA;AAAA,QAGO,oBACd,iBACA;AACA,UAAM,iBAAiB,MAAM,gBAAgB;AAE7C,SAAK,IAAI,OAAO,KACd,iDAAiD,eAAe;AAGlE,WAAO;AAAA;AAAA,EAGC,0BAA0B;AAClC,WAAO,KAAK,IAAI,OAAO,UACrB;AAAA;AAAA,EAIM,wBAAwB;AAChC,UAAM,4BAA4B,KAAK,IAAI,OAAO,uBAChD;AAGF,QAAI;AAEJ,QAAI,2BAA2B;AAC7B,2BAAqB,gBAAgB,OAAO,SAC1C,0BAA0B,SAAS,IAAI;AAAA;AAG3C,WAAO;AAAA;AAAA;;4BCjNT,SACyB;AACzB,QAAM,CAAE,UAAW,MAAM,kBAAkB,cAAc,SACtD,mBAAmB,QAAQ,iBAC3B;AACH,SAAO;AAAA;;;;;;"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Config } from '@backstage/config';
|
|
2
|
-
import express from 'express';
|
|
3
2
|
import { Logger } from 'winston';
|
|
4
|
-
import { KubernetesFetchError, FetchResponse, KubernetesRequestBody,
|
|
3
|
+
import { KubernetesFetchError, FetchResponse, KubernetesRequestBody, ObjectsByEntityResponse } from '@backstage/plugin-kubernetes-common';
|
|
4
|
+
import express from 'express';
|
|
5
5
|
|
|
6
6
|
interface ObjectFetchParams {
|
|
7
7
|
serviceId: string;
|
|
@@ -77,25 +77,16 @@ interface AWSClusterDetails extends ClusterDetails {
|
|
|
77
77
|
assumeRole?: string;
|
|
78
78
|
externalId?: string;
|
|
79
79
|
}
|
|
80
|
-
|
|
81
|
-
declare const DEFAULT_OBJECTS: ObjectToFetch[];
|
|
82
|
-
interface KubernetesFanOutHandlerOptions {
|
|
80
|
+
interface KubernetesObjectsProviderOptions {
|
|
83
81
|
logger: Logger;
|
|
84
82
|
fetcher: KubernetesFetcher;
|
|
85
83
|
serviceLocator: KubernetesServiceLocator;
|
|
86
84
|
customResources: CustomResource[];
|
|
87
85
|
objectTypesToFetch?: ObjectToFetch[];
|
|
88
86
|
}
|
|
89
|
-
declare
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
private readonly serviceLocator;
|
|
93
|
-
private readonly customResources;
|
|
94
|
-
private readonly objectTypesToFetch;
|
|
95
|
-
constructor({ logger, fetcher, serviceLocator, customResources, objectTypesToFetch, }: KubernetesFanOutHandlerOptions);
|
|
96
|
-
getKubernetesObjectsByEntity(requestBody: KubernetesRequestBody): Promise<{
|
|
97
|
-
items: ClusterObjects[];
|
|
98
|
-
}>;
|
|
87
|
+
declare type ObjectsByEntityRequest = KubernetesRequestBody;
|
|
88
|
+
interface KubernetesObjectsProvider {
|
|
89
|
+
getKubernetesObjectsByEntity(request: ObjectsByEntityRequest): Promise<ObjectsByEntityResponse>;
|
|
99
90
|
}
|
|
100
91
|
|
|
101
92
|
interface RouterOptions {
|
|
@@ -103,7 +94,59 @@ interface RouterOptions {
|
|
|
103
94
|
config: Config;
|
|
104
95
|
clusterSupplier?: KubernetesClustersSupplier;
|
|
105
96
|
}
|
|
106
|
-
|
|
97
|
+
/**
|
|
98
|
+
* creates and configure a new router for handling the kubernetes backend APIs
|
|
99
|
+
* @param options - specifies the options required by this plugin
|
|
100
|
+
* @returns a new router
|
|
101
|
+
* @deprecated Please use the new KubernetesBuilder instead like this
|
|
102
|
+
* ```
|
|
103
|
+
* import { KubernetesBuilder } from '@backstage/plugin-kubernetes-backend';
|
|
104
|
+
* const { router } = await KubernetesBuilder.createBuilder({
|
|
105
|
+
* logger,
|
|
106
|
+
* config,
|
|
107
|
+
* }).build();
|
|
108
|
+
* ```
|
|
109
|
+
*/
|
|
107
110
|
declare function createRouter(options: RouterOptions): Promise<express.Router>;
|
|
108
111
|
|
|
109
|
-
|
|
112
|
+
interface KubernetesEnvironment {
|
|
113
|
+
logger: Logger;
|
|
114
|
+
config: Config;
|
|
115
|
+
}
|
|
116
|
+
declare class KubernetesBuilder {
|
|
117
|
+
protected readonly env: KubernetesEnvironment;
|
|
118
|
+
private clusterSupplier?;
|
|
119
|
+
private objectsProvider?;
|
|
120
|
+
private fetcher?;
|
|
121
|
+
private serviceLocator?;
|
|
122
|
+
static createBuilder(env: KubernetesEnvironment): KubernetesBuilder;
|
|
123
|
+
constructor(env: KubernetesEnvironment);
|
|
124
|
+
build(): Promise<{
|
|
125
|
+
clusterDetails: ClusterDetails[];
|
|
126
|
+
clusterSupplier: KubernetesClustersSupplier;
|
|
127
|
+
customResources: CustomResource[];
|
|
128
|
+
fetcher: KubernetesFetcher;
|
|
129
|
+
objectsProvider: KubernetesObjectsProvider;
|
|
130
|
+
router: express.Router;
|
|
131
|
+
serviceLocator: KubernetesServiceLocator;
|
|
132
|
+
}>;
|
|
133
|
+
setClusterSupplier(clusterSupplier?: KubernetesClustersSupplier): this;
|
|
134
|
+
setObjectsProvider(objectsProvider?: KubernetesObjectsProvider): this;
|
|
135
|
+
setFetcher(fetcher?: KubernetesFetcher): this;
|
|
136
|
+
setServiceLocator(serviceLocator?: KubernetesServiceLocator): this;
|
|
137
|
+
protected buildCustomResources(): CustomResource[];
|
|
138
|
+
protected buildClusterSupplier(): KubernetesClustersSupplier;
|
|
139
|
+
protected buildObjectsProvider(options: KubernetesObjectsProviderOptions): KubernetesObjectsProvider;
|
|
140
|
+
protected buildFetcher(): KubernetesFetcher;
|
|
141
|
+
protected buildServiceLocator(method: ServiceLocatorMethod, clusterDetails: ClusterDetails[]): KubernetesServiceLocator;
|
|
142
|
+
protected buildMultiTenantServiceLocator(clusterDetails: ClusterDetails[]): KubernetesServiceLocator;
|
|
143
|
+
protected buildHttpServiceLocator(_clusterDetails: ClusterDetails[]): KubernetesServiceLocator;
|
|
144
|
+
protected buildRouter(objectsProvider: KubernetesObjectsProvider, clusterDetails: ClusterDetails[]): express.Router;
|
|
145
|
+
protected fetchClusterDetails(clusterSupplier: KubernetesClustersSupplier): Promise<ClusterDetails[]>;
|
|
146
|
+
protected getServiceLocatorMethod(): ServiceLocatorMethod;
|
|
147
|
+
protected getObjectTypesToFetch(): ObjectToFetch[] | undefined;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
declare const DEFAULT_OBJECTS: ObjectToFetch[];
|
|
151
|
+
|
|
152
|
+
export { AWSClusterDetails, ClusterDetails, CustomResource, DEFAULT_OBJECTS, FetchResponseWrapper, GKEClusterDetails, KubernetesBuilder, KubernetesClustersSupplier, KubernetesEnvironment, KubernetesFetcher, KubernetesObjectTypes, KubernetesObjectsProvider, KubernetesObjectsProviderOptions, KubernetesServiceLocator, ObjectFetchParams, ObjectToFetch, ObjectsByEntityRequest, RouterOptions, ServiceAccountClusterDetails, ServiceLocatorMethod, createRouter };
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@backstage/plugin-kubernetes-backend",
|
|
3
3
|
"description": "A Backstage backend plugin that integrates towards Kubernetes",
|
|
4
|
-
"version": "0.0.0-nightly-
|
|
4
|
+
"version": "0.0.0-nightly-202191722049",
|
|
5
5
|
"main": "dist/index.cjs.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
7
7
|
"license": "Apache-2.0",
|
|
@@ -32,10 +32,10 @@
|
|
|
32
32
|
"clean": "backstage-cli clean"
|
|
33
33
|
},
|
|
34
34
|
"dependencies": {
|
|
35
|
-
"@backstage/backend-common": "^0.
|
|
36
|
-
"@backstage/catalog-model": "^0.
|
|
35
|
+
"@backstage/backend-common": "^0.0.0-nightly-202191722049",
|
|
36
|
+
"@backstage/catalog-model": "^0.0.0-nightly-202191722049",
|
|
37
37
|
"@backstage/config": "^0.1.10",
|
|
38
|
-
"@backstage/plugin-kubernetes-common": "^0.
|
|
38
|
+
"@backstage/plugin-kubernetes-common": "^0.0.0-nightly-202191722049",
|
|
39
39
|
"@google-cloud/container": "^2.2.0",
|
|
40
40
|
"@kubernetes/client-node": "^0.15.0",
|
|
41
41
|
"@types/express": "^4.17.6",
|
|
@@ -54,7 +54,7 @@
|
|
|
54
54
|
"yn": "^4.0.0"
|
|
55
55
|
},
|
|
56
56
|
"devDependencies": {
|
|
57
|
-
"@backstage/cli": "^0.0.0-nightly-
|
|
57
|
+
"@backstage/cli": "^0.0.0-nightly-202191722049",
|
|
58
58
|
"@types/aws4": "^1.5.1",
|
|
59
59
|
"supertest": "^6.1.3",
|
|
60
60
|
"aws-sdk-mock": "^5.2.1",
|