Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: manage default uri plugins for DevWorkspaces #426

Merged
merged 1 commit into from
Dec 24, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions local-start.sh
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ Arguments:
Env vars:
KUBECONFIG : Kubeconfig file location. Default: "$HOME/.kube/config"
CHE_NAMESPACE : kubernetes namespace where Che Cluster should be looked into. Default: "eclipse-che"
CHE_CRD_OBJECT_NAME : kubernetes CRD object name. Default: "eclipse-che"
CHECLUSTER_CR_NAME : kubernetes CRD object name. Default: "eclipse-che"
Examples:
$0
$0 --force-build
Expand All @@ -38,9 +38,10 @@ parse_args() {
FORCE_BUILD="false"
# Init Che Namespace with the default value if it's not set
CHE_NAMESPACE="${CHE_NAMESPACE:-eclipse-che}"
CHECLUSTER_CR_NAMESPACE="${CHE_NAMESPACE}"

# Init Che CRD object name with the default value if it's not set
CHE_CRD_OBJECT_NAME="${CHE_CRD_OBJECT_NAME:-eclipse-che}"
CHECLUSTER_CR_NAME="${CHECLUSTER_CR_NAME:-eclipse-che}"

# guide backend to use the current cluster from kubeconfig
export LOCAL_RUN="true"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ const GROUP = 'org.eclipse.che';
const VERSION = 'v1';
const PLURAL = 'checlusters';

const NAME = process.env.CHE_CRD_OBJECT_NAME;
const NAMESPACE = process.env.CHE_NAMESPACE;
const NAME = process.env.CHECLUSTER_CR_NAME;
const NAMESPACE = process.env.CHECLUSTER_CR_NAMESPACE;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.


export class ServerConfigApi implements IServerConfigApi {
private readonly customObjectAPI: k8s.CustomObjectsApi;
Expand All @@ -36,7 +36,7 @@ export class ServerConfigApi implements IServerConfigApi {
throw createError(
undefined,
CUSTOM_RECOURSE_DEFINITIONS_API_ERROR_LABEL,
'Mandatory environment variables are not defined: $CHE_NAMESPACE, $CHE_CRD_OBJECT_NAME',
'Mandatory environment variables are not defined: $CHECLUSTER_CR_NAMESPACE, $CHECLUSTER_CR_NAME',
);
}

Expand Down
2 changes: 2 additions & 0 deletions packages/dashboard-frontend/src/inversify.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
} from './services/workspace-client/devworkspace/devWorkspaceClient';
import { DevWorkspaceEditorProcessTheia } from './services/workspace-client/devworkspace/DevWorkspaceEditorProcessTheia';
import { DevWorkspaceEditorProcessCode } from './services/workspace-client/devworkspace/DevWorkspaceEditorProcessCode';
import { DevWorkspaceDefaultPluginsHandler } from './services/workspace-client/devworkspace/DevWorkspaceDefaultPluginsHandler';

const container = new Container();
const { lazyInject } = getDecorators(container);
Expand All @@ -38,5 +39,6 @@ container.bind(DevWorkspaceClient).toSelf().inSingletonScope();
container.bind(IDevWorkspaceEditorProcess).to(DevWorkspaceEditorProcessTheia).inSingletonScope();
container.bind(IDevWorkspaceEditorProcess).to(DevWorkspaceEditorProcessCode).inSingletonScope();
container.bind(AppAlerts).toSelf().inSingletonScope();
container.bind(DevWorkspaceDefaultPluginsHandler).toSelf().inSingletonScope();

export { container, lazyInject };
13 changes: 13 additions & 0 deletions packages/dashboard-frontend/src/services/bootstrap/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ export default class Bootstrap {
return this.fetchDevfileSchema();
}),
this.fetchDwPlugins(settings),
this.fetchDefaultDwPlugins(settings),
this.fetchRegistriesMetadata(settings),
this.updateDevWorkspaceTemplates(settings),
this.fetchWorkspaces(),
Expand Down Expand Up @@ -175,6 +176,18 @@ export default class Bootstrap {
}
}

private async fetchDefaultDwPlugins(settings: che.WorkspaceSettings): Promise<void> {
if (!isDevworkspacesEnabled(settings)) {
return;
}
const { requestDwDefaultPlugins } = DwPluginsStore.actionCreators;
try {
await requestDwDefaultPlugins()(this.store.dispatch, this.store.getState, undefined);
} catch (e) {
console.error('Failed to retrieve default plug-ins.', e);
}
}

private async updateDevWorkspaceTemplates(settings: che.WorkspaceSettings): Promise<void> {
if (!isDevworkspacesEnabled(settings)) {
return;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
* Copyright (c) 2018-2021 Red Hat, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/

import axios from 'axios';
import common from '@eclipse-che/common';
import { prefix } from './const';
import { api } from '@eclipse-che/common';

/**
* Returns an array of default plug-ins per editor
*
* @returns Promise resolving with the array of default plug-ins for the specified editor
*/
export async function getDefaultPlugins(): Promise<api.IWorkspacesDefaultPlugins[]> {
const url = `${prefix}/server-config/default-plugins`;
try {
const response = await axios.get(url);
return response.data ? response.data : [];
} catch (e) {
throw `Failed to fetch default plugins. ${common.helpers.errors.getMessage(e)}`;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
/*
* Copyright (c) 2018-2021 Red Hat, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/

import * as DwApi from '../../dashboard-backend-client/devWorkspaceApi';
import devfileApi from '../../devfileApi';
import { api } from '@eclipse-che/common';
import { createHash } from 'crypto';
import { injectable } from 'inversify';
import { V1alpha2DevWorkspaceSpecTemplateComponents } from '@devfile/api';
import { WorkspacesDefaultPlugins } from 'dashboard-frontend/src/store/Plugins/devWorkspacePlugins';

const DEFAULT_PLUGIN_ATTRIBUTE = 'che.eclipse.org/default-plugin';

/**
* This class manages the default plugins defined in
* the DevWorkspace's spec.template.components array.
*/
@injectable()
export class DevWorkspaceDefaultPluginsHandler {
public async handle(
workspace: devfileApi.DevWorkspace,
editorId: string,
defaultPlugins: WorkspacesDefaultPlugins,
): Promise<void> {
if (!defaultPlugins[editorId]) {
return;
}

const componentsUpdated = this.handleUriPlugins(workspace, defaultPlugins[editorId]);
if (componentsUpdated) {
this.patchWorkspaceComponents(workspace);
}
}

/**
* Manages the default uri plugins from the devworkspace's spec.template.components
* @param workspace A devworkspace to manage default plugins for
* @param defaultPlugins The set of current default plugins uris
* @returns true if the devworkspace's spec.template.components has been updated
*/
private handleUriPlugins(workspace: devfileApi.DevWorkspace, defaultPlugins: string[]): boolean {
const defaultUriPlugins = new Set(
defaultPlugins.filter(plugin => {
if (this.isUri(plugin)) {
return true;
}
console.log(`Default plugin ${plugin} is not a uri. Ignoring.`);
return false;
}),
);

let componentsUpdated = this.removeOldDefaultUriPlugins(workspace, defaultUriPlugins);
defaultUriPlugins.forEach(plugin => {
const hash = createHash('MD5').update(plugin).digest('hex').substring(0, 20).toLowerCase();
const added = this.addDefaultPluginByUri(workspace, 'default-' + hash, plugin);
componentsUpdated = added || componentsUpdated;
});

return componentsUpdated;
}

private isUri(str: string): boolean {
try {
new URL(str);
return true;
} catch (err) {
return false;
}
}

/**
* Checks if there are default plugins in the workspace that are not
* specified in defaultUriPlugins. If such plugins are found, this function
* removes them.
* @param workspace A devworkspace to remove old default plugins for
* @param defaultUriPlugins The set of current default plugins
* @returns true if a plugin has been removed, false otherwise
*/
private removeOldDefaultUriPlugins(
workspace: devfileApi.DevWorkspace,
defaultUriPlugins: Set<string>,
): boolean {
if (!workspace.spec.template.components) {
return false;
}

const components = workspace.spec.template.components.filter(component => {
if (!this.isDefaultPluginComponent(component) || !component.plugin?.uri) {
// component is not a default uri plugin, keep component.
return true;
}
return defaultUriPlugins.has(component.plugin.uri);
});

const removed = workspace.spec.template.components.length !== components.length;
workspace.spec.template.components = components;
return removed;
}

/**
* Returns true if component is a default plugin managed by this class
* @param component The component to check
* @returns true if component is a default plugin managed by this class
*/
private isDefaultPluginComponent(component: V1alpha2DevWorkspaceSpecTemplateComponents): boolean {
return component.attributes && component.attributes[DEFAULT_PLUGIN_ATTRIBUTE]
? component.attributes[DEFAULT_PLUGIN_ATTRIBUTE].toString() === 'true'
: false;
}

/**
* Adds a default plugin to the workspace by uri if the default plugin does not
* already exist
* @param workspace A devworkspace
* @param pluginName The name of the plugin
* @param pluginUri The uri of the plugin
* @returns true if the default plugin has been added
*/
private addDefaultPluginByUri(
workspace: devfileApi.DevWorkspace,
pluginName: string,
pluginUri: string,
): boolean {
if (!workspace.spec.template.components) {
workspace.spec.template.components = [];
}

if (workspace.spec.template.components.find(component => component.name === pluginName)) {
// plugin already exists
return false;
}

workspace.spec.template.components.push({
name: pluginName,
attributes: { [DEFAULT_PLUGIN_ATTRIBUTE]: true },
plugin: { uri: pluginUri },
});
return true;
}

private async patchWorkspaceComponents(workspace: devfileApi.DevWorkspace) {
const patch: api.IPatch[] = [
{
op: 'replace',
path: '/spec/template/components',
value: workspace.spec.template.components,
},
];
return DwApi.patchWorkspace(workspace.metadata.namespace, workspace.metadata.name, patch);
}
}
Loading