grafana/public/app/angular/components/plugin_component.ts

250 lines
8.0 KiB
TypeScript
Raw Normal View History

import angular, { ILocationService } from 'angular';
import { each } from 'lodash';
import { DataSourceApi, PanelEvents } from '@grafana/data';
import coreModule from 'app/angular/core_module';
import config from 'app/core/config';
import { importPanelPlugin } from '../../features/plugins/importPanelPlugin';
import { importDataSourcePlugin, importAppPlugin } from '../../features/plugins/plugin_loader';
coreModule.directive('pluginComponent', ['$compile', '$http', '$templateCache', '$location', pluginDirectiveLoader]);
function pluginDirectiveLoader($compile: any, $http: any, $templateCache: any, $location: ILocationService) {
function getTemplate(component: { template: any; templateUrl: any }) {
if (component.template) {
return Promise.resolve(component.template);
}
const cached = $templateCache.get(component.templateUrl);
if (cached) {
return Promise.resolve(cached);
}
return $http.get(component.templateUrl).then((res: any) => {
return res.data;
});
}
function relativeTemplateUrlToAbs(templateUrl: string, baseUrl: string) {
if (!templateUrl) {
return undefined;
}
2017-12-20 05:33:33 -06:00
if (templateUrl.indexOf('public') === 0) {
return templateUrl;
}
Plugins: Allow loading panel plugins from a CDN (#59096) * POC: Plugins CDN reverse proxy * CDN proxy POC: changed env var names * Add authorization: false for /public path in frontend plugin loader * Moved CDN settings to Cfg, add some comments * Fix error 500 in asset fetch if plugin is not using CDN * Fix EnterpriseLicensePath declared twice * Fix linter complaining about whitespaces * Plugins CDN: Skip signature verification for CDN plugins * Plugins CDN: Skip manifest and signature check for cdn plugins * Plugins: use IsValid() and IsInternal() rather than equality checks * Plugins CDN: remove comment * Plugins CDN: Fix seeker can't seek when serving plugins from local fs * Plugins CDN: add back error codes in getLocalPluginAssets * Plugins CDN: call asset.Close() rather than asset.readSeekCloser.Close() * Plugins CDN: Fix panic in JsonApiErr when errorMessageCoder wraps a nil error * Plugins CDN: Add error handling to proxyCDNPluginAsset * Plugins CDN: replace errorMessageCoder with errutil * Plugins CDN POC: expose cdn plugin paths to frontend for system.js * Plugins CDN: Fix cdn plugins showing as unsigned in frontend * WIP: Add support for formatted URL * Fix missing cdnPluginsBaseURLs in GrafanaConfig * Plugins CDN: Remove reverse proxy mode and reverse proxy references * Plugins CDN: Simplify asset serving logic * Plugins CDN: sanitize redirect path * Plugins CDN: Removed unused pluginAsset type * Plugins CDN: Removed system.js changes * Plugins CDN: Return different system.js baseURL and module for cdn plugins * Plugins CDN: Ensure CDN is disabled for non-external plugins * lint * Plugins CDN: serve images and screenshots from CDN, refactoring * Lint * Plugins CDN: Fix URLs for system.js (baseUrl and module) * Plugins CDN: Add more tests for RelativeURLForSystemJS * Plugins CDN: Iterate only on apps when preloading * Plugins CDN: Refactoring * Plugins CDN: Add comments to url_constructor.go * Plugins CDN: Update defaultHGPluginsCDNBaseURL * Plugins CDN: undo extract meta from system js config * refactor(plugins): migrate systemjs css plugin to typescript * feat(plugins): introduce systemjs cdn loader plugin * feat(plugins): add systemjs load type * Plugins CDN: Removed RelativeURLForSystemJS * Plugins CDN: Log backend redirect hits along with plugin info * Plugins CDN: Add pluginsCDNBasePath to getFrontendSettingsMap * feat(plugins): introduce cdn loading for angular plugins * refactor(plugins): move systemjs cache buster into systemjsplugins directory * Plugins CDN: Rename pluginsCDNBasePath to pluginsCDNBaseURL * refactor(plugins): introduce pluginsCDNBaseURL to the frontend * Plugins CDN: Renamed "cdn base path" to "cdn url template" in backend * Plugins CDN: lint * merge with main * Instrumentation: Add prometheus counter for backend hits, log from Info to Warn * Config: Changed key from plugins_cdn.url to plugins.plugins_cdn_base_url * CDN: Add backend tests * Lint: goimports * Default CDN URL to empty string, * Do not use CDN in setImages and module if the url template is empty * CDN: Backend: Add test for frontend settings * CDN: Do not log missing module.js warn if plugin is being loaded from CDN * CDN: Add backend test for CDN plugin loader * Removed 'cdn' signature level, switch to 'valid' * Fix pfs.TestParseTreeTestdata for cdn plugin testdata dir * Fix TestLoader_Load * Fix gocyclo complexity of loadPlugins * Plugins CDN: Moved prometheus metric to api package, removed asset_path label * Fix missing in config * Changes after review * Add pluginscdn.Service * Fix tests * Refactoring * Moved all remaining CDN checks inside pluginscdn.Service * CDN url constructor: Renamed stringURLFor to stringPath * CDN: Moved asset URL functionality to assetpath service * CDN: Renamed HasCDN() to IsEnabled() * CDN: Replace assert with require * CDN: Changes after review * Assetpath: Handle url.Parse error * Fix plugin_resource_test * CDN: Change fallback redirect from 302 to 307 * goimports * Fix tests * Switch to contextmodel.ReqContext in plugins.go Co-authored-by: Will Browne <will.browne@grafana.com> Co-authored-by: Jack Westbrook <jack.westbrook@gmail.com>
2023-01-27 08:08:17 -06:00
2017-12-20 05:33:33 -06:00
return baseUrl + '/' + templateUrl;
}
function getPluginComponentDirective(options: any) {
Plugins: Bump SystemJS to 6.14.2 (#70068) * chore(plugins): bump systemjs to latest version * refactor(plugins): switch runtime over to use latest systemjs, add typings * refactor(plugins): use latest systemjs APIs for runtime dependency resolution * refactor(plugins): return valid urls from backend for latest systemjs import to work * revert(plugins): remove cfg from assetpath in favour of relative paths * fix(plugins): useDefault for systemjs deps to solve undefined errors * feat(plugins): add basic support for loading plugins via CDN * fix(plugins): load nested plugins with latest systemjs * feat(plugins): add back ability to transform plugin src for cdns * feat(plugins): get caching for module.js working, clean up * refactor(plugin_loader): create buildImportMap fn and more clean up * refactor(angularapp): use buildImportMap for dependencies and clean up * test(plugin_loader): fix failing test due to systemjs update * test(jest): mock systemjs amd extra in tests to prevent it breaking tests * chore(plugins): remove systemjs module-types extra, already included with system * fix(plugins): update key for invalidating cached plugins * fix: move systemjs amd define to another global so monaco can load * refactor(plugins): clean up cache buster and tests * chore(plugins): remove debug * refactor(plugins): move systemjs define to keep global cleaner * fix(plugins): set useDefault so system modules lodash references dont fail * feat(plugins): hook systemjs onload so stylesheets are applied to the dom * refactor(plugins): wrap amd formatted plugins in iife to prevent define collision * feat(plugins): support system module format for legacy plugins * test(plugincachebuster): update tests to match latest implementation * test(plugins-loader): fix up tests post module property change * fix test * Update pkg/plugins/manager/loader/assetpath/assetpath.go Co-authored-by: Will Browne <wbrowne@users.noreply.github.com> * chore(plugin_loader): remove stray import from merge conflict * Revert "Update pkg/plugins/manager/loader/assetpath/assetpath.go" This reverts commit 0df57d1cf20f49c22c93369001c70aae46a97c42. * fix(plugin_loader): set use default for shared plugin dependencies * refactor(plugins): use leading slash for Module and BaseUrl * fix(plugins): fix resolve appending extension to cache query param * refactor(plugins): align baseurl and module paths * refactor(plugins): update builtInPlugins keys to match naming convention * refactor(plugins): minor loader clean up, fix up types * test(plugins): fix failing tests * refactor(plugins): rename cache buster systemjs plugin to cache * refactor(plugins): separate plugin_loader into smaller files * chore(plugins): clean up plugin_loader types * chore(plugin_sandbox): fix typescript error * chore(npm): remove unplug debug and pin systemjs to 6.14.1 * refactor(plugins-cdn): update loaders to use absolute module url from backend * fix(plugins): escape period in systemjs module regex * chore(plugins): delete redundant systemjs plugins * refactor(plugin_loader): move hooks into own file, add types * test(plugins): add tests for systemjs loader hooks * chore(plugins): rename systemjshooks file * chore(plugins): remove redundant systemjs cdn backend code * fix(plugins): handle loading with config.appSubUrl * chore(plugins): delete redundant plugin-cdn angular code * test(plugins): fix failing systemjs test missing pluginsCDNBaseUrl * refactor(plugins): backend provides base and module properties with AppSubUrl * fix(plugins): consider AppSubUrl for plugin logos * fix(plugins): use isHostedOnCDN util when checking for cdn hosted plugins * add new appSubURL field to config * refactor relative URL func * fix path for core app * refactor asset path input * fix(plugins): catch errors in loadPluginCss * feat(plugins-cdn): selectively transform sourceMapURL * re-add deleted test case * chore(plugins): bump to latest systemjs@6.14.2 * feat(plugins): add systemjs-cjs-extra for loading commonjs plugins --------- Co-authored-by: Will Browne <will.browne@grafana.com> Co-authored-by: Will Browne <wbrowne@users.noreply.github.com>
2023-08-31 08:45:44 -05:00
// handle relative template urls for plugin templates
options.Component.templateUrl = relativeTemplateUrlToAbs(options.Component.templateUrl, options.baseUrl);
return () => {
return {
templateUrl: options.Component.templateUrl,
template: options.Component.template,
2017-12-20 05:33:33 -06:00
restrict: 'E',
controller: options.Component,
2017-12-20 05:33:33 -06:00
controllerAs: 'ctrl',
bindToController: true,
scope: options.bindings,
link: (scope: any, elem: any, attrs: any, ctrl: any) => {
if (ctrl.link) {
ctrl.link(scope, elem, attrs, ctrl);
}
if (ctrl.init) {
ctrl.init();
}
2017-12-20 05:33:33 -06:00
},
};
};
}
function loadPanelComponentInfo(scope: any, attrs: any) {
const componentInfo: any = {
2017-12-20 05:33:33 -06:00
name: 'panel-plugin-' + scope.panel.type,
bindings: { dashboard: '=', panel: '=', row: '=' },
attrs: {
2017-12-20 05:33:33 -06:00
dashboard: 'dashboard',
panel: 'panel',
class: 'panel-height-helper',
},
};
const panelInfo = config.panels[scope.panel.type];
return importPanelPlugin(panelInfo.id).then((panelPlugin) => {
const PanelCtrl = panelPlugin.angularPanelCtrl;
componentInfo.Component = PanelCtrl;
if (!PanelCtrl || PanelCtrl.registered) {
return componentInfo;
}
if (PanelCtrl.templatePromise) {
return PanelCtrl.templatePromise.then((res: any) => {
return componentInfo;
});
}
if (panelInfo) {
Plugins: Bump SystemJS to 6.14.2 (#70068) * chore(plugins): bump systemjs to latest version * refactor(plugins): switch runtime over to use latest systemjs, add typings * refactor(plugins): use latest systemjs APIs for runtime dependency resolution * refactor(plugins): return valid urls from backend for latest systemjs import to work * revert(plugins): remove cfg from assetpath in favour of relative paths * fix(plugins): useDefault for systemjs deps to solve undefined errors * feat(plugins): add basic support for loading plugins via CDN * fix(plugins): load nested plugins with latest systemjs * feat(plugins): add back ability to transform plugin src for cdns * feat(plugins): get caching for module.js working, clean up * refactor(plugin_loader): create buildImportMap fn and more clean up * refactor(angularapp): use buildImportMap for dependencies and clean up * test(plugin_loader): fix failing test due to systemjs update * test(jest): mock systemjs amd extra in tests to prevent it breaking tests * chore(plugins): remove systemjs module-types extra, already included with system * fix(plugins): update key for invalidating cached plugins * fix: move systemjs amd define to another global so monaco can load * refactor(plugins): clean up cache buster and tests * chore(plugins): remove debug * refactor(plugins): move systemjs define to keep global cleaner * fix(plugins): set useDefault so system modules lodash references dont fail * feat(plugins): hook systemjs onload so stylesheets are applied to the dom * refactor(plugins): wrap amd formatted plugins in iife to prevent define collision * feat(plugins): support system module format for legacy plugins * test(plugincachebuster): update tests to match latest implementation * test(plugins-loader): fix up tests post module property change * fix test * Update pkg/plugins/manager/loader/assetpath/assetpath.go Co-authored-by: Will Browne <wbrowne@users.noreply.github.com> * chore(plugin_loader): remove stray import from merge conflict * Revert "Update pkg/plugins/manager/loader/assetpath/assetpath.go" This reverts commit 0df57d1cf20f49c22c93369001c70aae46a97c42. * fix(plugin_loader): set use default for shared plugin dependencies * refactor(plugins): use leading slash for Module and BaseUrl * fix(plugins): fix resolve appending extension to cache query param * refactor(plugins): align baseurl and module paths * refactor(plugins): update builtInPlugins keys to match naming convention * refactor(plugins): minor loader clean up, fix up types * test(plugins): fix failing tests * refactor(plugins): rename cache buster systemjs plugin to cache * refactor(plugins): separate plugin_loader into smaller files * chore(plugins): clean up plugin_loader types * chore(plugin_sandbox): fix typescript error * chore(npm): remove unplug debug and pin systemjs to 6.14.1 * refactor(plugins-cdn): update loaders to use absolute module url from backend * fix(plugins): escape period in systemjs module regex * chore(plugins): delete redundant systemjs plugins * refactor(plugin_loader): move hooks into own file, add types * test(plugins): add tests for systemjs loader hooks * chore(plugins): rename systemjshooks file * chore(plugins): remove redundant systemjs cdn backend code * fix(plugins): handle loading with config.appSubUrl * chore(plugins): delete redundant plugin-cdn angular code * test(plugins): fix failing systemjs test missing pluginsCDNBaseUrl * refactor(plugins): backend provides base and module properties with AppSubUrl * fix(plugins): consider AppSubUrl for plugin logos * fix(plugins): use isHostedOnCDN util when checking for cdn hosted plugins * add new appSubURL field to config * refactor relative URL func * fix path for core app * refactor asset path input * fix(plugins): catch errors in loadPluginCss * feat(plugins-cdn): selectively transform sourceMapURL * re-add deleted test case * chore(plugins): bump to latest systemjs@6.14.2 * feat(plugins): add systemjs-cjs-extra for loading commonjs plugins --------- Co-authored-by: Will Browne <will.browne@grafana.com> Co-authored-by: Will Browne <wbrowne@users.noreply.github.com>
2023-08-31 08:45:44 -05:00
PanelCtrl.templateUrl = relativeTemplateUrlToAbs(PanelCtrl.templateUrl, panelInfo.baseUrl);
}
PanelCtrl.templatePromise = getTemplate(PanelCtrl).then((template: any) => {
PanelCtrl.templateUrl = null;
2018-12-03 05:31:55 -06:00
PanelCtrl.template = `<grafana-panel ctrl="ctrl" class="panel-height-helper">${template}</grafana-panel>`;
Plugins: Allow loading panel plugins from a CDN (#59096) * POC: Plugins CDN reverse proxy * CDN proxy POC: changed env var names * Add authorization: false for /public path in frontend plugin loader * Moved CDN settings to Cfg, add some comments * Fix error 500 in asset fetch if plugin is not using CDN * Fix EnterpriseLicensePath declared twice * Fix linter complaining about whitespaces * Plugins CDN: Skip signature verification for CDN plugins * Plugins CDN: Skip manifest and signature check for cdn plugins * Plugins: use IsValid() and IsInternal() rather than equality checks * Plugins CDN: remove comment * Plugins CDN: Fix seeker can't seek when serving plugins from local fs * Plugins CDN: add back error codes in getLocalPluginAssets * Plugins CDN: call asset.Close() rather than asset.readSeekCloser.Close() * Plugins CDN: Fix panic in JsonApiErr when errorMessageCoder wraps a nil error * Plugins CDN: Add error handling to proxyCDNPluginAsset * Plugins CDN: replace errorMessageCoder with errutil * Plugins CDN POC: expose cdn plugin paths to frontend for system.js * Plugins CDN: Fix cdn plugins showing as unsigned in frontend * WIP: Add support for formatted URL * Fix missing cdnPluginsBaseURLs in GrafanaConfig * Plugins CDN: Remove reverse proxy mode and reverse proxy references * Plugins CDN: Simplify asset serving logic * Plugins CDN: sanitize redirect path * Plugins CDN: Removed unused pluginAsset type * Plugins CDN: Removed system.js changes * Plugins CDN: Return different system.js baseURL and module for cdn plugins * Plugins CDN: Ensure CDN is disabled for non-external plugins * lint * Plugins CDN: serve images and screenshots from CDN, refactoring * Lint * Plugins CDN: Fix URLs for system.js (baseUrl and module) * Plugins CDN: Add more tests for RelativeURLForSystemJS * Plugins CDN: Iterate only on apps when preloading * Plugins CDN: Refactoring * Plugins CDN: Add comments to url_constructor.go * Plugins CDN: Update defaultHGPluginsCDNBaseURL * Plugins CDN: undo extract meta from system js config * refactor(plugins): migrate systemjs css plugin to typescript * feat(plugins): introduce systemjs cdn loader plugin * feat(plugins): add systemjs load type * Plugins CDN: Removed RelativeURLForSystemJS * Plugins CDN: Log backend redirect hits along with plugin info * Plugins CDN: Add pluginsCDNBasePath to getFrontendSettingsMap * feat(plugins): introduce cdn loading for angular plugins * refactor(plugins): move systemjs cache buster into systemjsplugins directory * Plugins CDN: Rename pluginsCDNBasePath to pluginsCDNBaseURL * refactor(plugins): introduce pluginsCDNBaseURL to the frontend * Plugins CDN: Renamed "cdn base path" to "cdn url template" in backend * Plugins CDN: lint * merge with main * Instrumentation: Add prometheus counter for backend hits, log from Info to Warn * Config: Changed key from plugins_cdn.url to plugins.plugins_cdn_base_url * CDN: Add backend tests * Lint: goimports * Default CDN URL to empty string, * Do not use CDN in setImages and module if the url template is empty * CDN: Backend: Add test for frontend settings * CDN: Do not log missing module.js warn if plugin is being loaded from CDN * CDN: Add backend test for CDN plugin loader * Removed 'cdn' signature level, switch to 'valid' * Fix pfs.TestParseTreeTestdata for cdn plugin testdata dir * Fix TestLoader_Load * Fix gocyclo complexity of loadPlugins * Plugins CDN: Moved prometheus metric to api package, removed asset_path label * Fix missing in config * Changes after review * Add pluginscdn.Service * Fix tests * Refactoring * Moved all remaining CDN checks inside pluginscdn.Service * CDN url constructor: Renamed stringURLFor to stringPath * CDN: Moved asset URL functionality to assetpath service * CDN: Renamed HasCDN() to IsEnabled() * CDN: Replace assert with require * CDN: Changes after review * Assetpath: Handle url.Parse error * Fix plugin_resource_test * CDN: Change fallback redirect from 302 to 307 * goimports * Fix tests * Switch to contextmodel.ReqContext in plugins.go Co-authored-by: Will Browne <will.browne@grafana.com> Co-authored-by: Jack Westbrook <jack.westbrook@gmail.com>
2023-01-27 08:08:17 -06:00
return { ...componentInfo, baseUrl: panelInfo.baseUrl };
});
return PanelCtrl.templatePromise;
});
}
function getModule(scope: any, attrs: any): any {
switch (attrs.type) {
// QueryCtrl
2017-12-20 05:33:33 -06:00
case 'query-ctrl': {
const ds: DataSourceApi = scope.ctrl.datasource as DataSourceApi;
return Promise.resolve({
baseUrl: ds.meta.baseUrl,
name: 'query-ctrl-' + ds.meta.id,
bindings: { target: '=', panelCtrl: '=', datasource: '=' },
attrs: {
target: 'ctrl.target',
'panel-ctrl': 'ctrl',
datasource: 'ctrl.datasource',
},
Component: ds.components!.QueryCtrl,
});
}
// Annotations
2017-12-20 05:33:33 -06:00
case 'annotations-query-ctrl': {
const baseUrl = scope.ctrl.currentDatasource.meta.baseUrl;
const pluginId = scope.ctrl.currentDatasource.meta.id;
return importDataSourcePlugin(scope.ctrl.currentDatasource.meta).then((dsPlugin) => {
return {
baseUrl,
name: 'annotations-query-ctrl-' + pluginId,
2017-12-20 05:33:33 -06:00
bindings: { annotation: '=', datasource: '=' },
attrs: {
2017-12-20 05:33:33 -06:00
annotation: 'ctrl.currentAnnotation',
datasource: 'ctrl.currentDatasource',
},
Component: dsPlugin.components.AnnotationsQueryCtrl,
};
});
}
// Datasource ConfigCtrl
2017-12-20 05:33:33 -06:00
case 'datasource-config-ctrl': {
const dsMeta = scope.ctrl.datasourceMeta;
const angularUrl = $location.url();
return importDataSourcePlugin(dsMeta).then((dsPlugin) => {
scope.$watch(
'ctrl.current',
() => {
// This watcher can trigger when we navigate away due to late digests
// This check is to stop onModelChanged from being called when navigating away
// as it triggers a redux action which comes before the angular $routeChangeSucces and
// This makes the bridgeSrv think location changed from redux before detecting it was actually
// changed from angular.
if (angularUrl === $location.url()) {
scope.onModelChanged(scope.ctrl.current);
}
},
true
);
return {
baseUrl: dsMeta.baseUrl,
name: 'ds-config-' + dsMeta.id,
bindings: { meta: '=', current: '=' },
attrs: { meta: 'ctrl.datasourceMeta', current: 'ctrl.current' },
Component: dsPlugin.angularConfigCtrl,
};
});
}
// AppConfigCtrl
2017-12-20 05:33:33 -06:00
case 'app-config-ctrl': {
const model = scope.ctrl.model;
return importAppPlugin(model).then((appPlugin) => {
return {
baseUrl: model.baseUrl,
2017-12-20 05:33:33 -06:00
name: 'app-config-' + model.id,
bindings: { appModel: '=', appEditCtrl: '=' },
attrs: { 'app-model': 'ctrl.model', 'app-edit-ctrl': 'ctrl' },
Component: appPlugin.angularConfigCtrl,
};
});
}
// Panel
2017-12-20 05:33:33 -06:00
case 'panel': {
return loadPanelComponentInfo(scope, attrs);
}
default: {
return Promise.reject({
2017-12-20 05:33:33 -06:00
message: 'Could not find component type: ' + attrs.type,
});
}
}
}
function appendAndCompile(scope: any, elem: JQuery, componentInfo: any) {
const child = angular.element(document.createElement(componentInfo.name));
each(componentInfo.attrs, (value, key) => {
child.attr(key, value);
});
$compile(child)(scope);
elem.empty();
// let a binding digest cycle complete before adding to dom
setTimeout(() => {
scope.$applyAsync(() => {
elem.append(child);
setTimeout(() => {
scope.$applyAsync(() => {
scope.$broadcast(PanelEvents.componentDidMount.name);
});
});
});
});
}
function registerPluginComponent(scope: any, elem: JQuery, attrs: any, componentInfo: any) {
if (componentInfo.notFound) {
elem.empty();
return;
}
if (!componentInfo.Component) {
throw {
message: 'Failed to find exported plugin component for ' + componentInfo.name,
};
}
if (!componentInfo.Component.registered) {
const directiveName = attrs.$normalize(componentInfo.name);
const directiveFn = getPluginComponentDirective(componentInfo);
coreModule.directive(directiveName, directiveFn);
componentInfo.Component.registered = true;
}
appendAndCompile(scope, elem, componentInfo);
}
return {
2017-12-20 05:33:33 -06:00
restrict: 'E',
link: (scope: any, elem: JQuery, attrs: any) => {
getModule(scope, attrs)
.then((componentInfo: any) => {
registerPluginComponent(scope, elem, attrs, componentInfo);
})
.catch((err: any) => {
console.error('Plugin component error', err);
});
2017-12-20 05:33:33 -06:00
},
};
}