datasource.ts 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. import { cloneDeep, upperFirst } from 'lodash';
  2. import { forkJoin, Observable, of } from 'rxjs';
  3. import { map } from 'rxjs/operators';
  4. import {
  5. DataFrame,
  6. DataQueryRequest,
  7. DataQueryResponse,
  8. DataSourceApi,
  9. DataSourceInstanceSettings,
  10. LoadingState,
  11. ScopedVars,
  12. } from '@grafana/data';
  13. import { getTemplateSrv, TemplateSrv } from 'app/features/templating/template_srv';
  14. import AzureLogAnalyticsDatasource from './azure_log_analytics/azure_log_analytics_datasource';
  15. import AzureMonitorDatasource from './azure_monitor/azure_monitor_datasource';
  16. import AzureResourceGraphDatasource from './azure_resource_graph/azure_resource_graph_datasource';
  17. import ResourcePickerData from './resourcePicker/resourcePickerData';
  18. import { AzureDataSourceJsonData, AzureMonitorQuery, AzureQueryType, DatasourceValidationResult } from './types';
  19. import migrateAnnotation from './utils/migrateAnnotation';
  20. import { datasourceMigrations } from './utils/migrateQuery';
  21. import { VariableSupport } from './variables';
  22. export default class Datasource extends DataSourceApi<AzureMonitorQuery, AzureDataSourceJsonData> {
  23. annotations = {
  24. prepareAnnotation: migrateAnnotation,
  25. };
  26. azureMonitorDatasource: AzureMonitorDatasource;
  27. azureLogAnalyticsDatasource: AzureLogAnalyticsDatasource;
  28. resourcePickerData: ResourcePickerData;
  29. azureResourceGraphDatasource: AzureResourceGraphDatasource;
  30. pseudoDatasource: {
  31. [key in AzureQueryType]?: AzureMonitorDatasource | AzureLogAnalyticsDatasource | AzureResourceGraphDatasource;
  32. } = {};
  33. declare optionsKey: Record<AzureQueryType, string>;
  34. constructor(
  35. instanceSettings: DataSourceInstanceSettings<AzureDataSourceJsonData>,
  36. private readonly templateSrv: TemplateSrv = getTemplateSrv()
  37. ) {
  38. super(instanceSettings);
  39. this.azureMonitorDatasource = new AzureMonitorDatasource(instanceSettings);
  40. this.azureLogAnalyticsDatasource = new AzureLogAnalyticsDatasource(instanceSettings);
  41. this.azureResourceGraphDatasource = new AzureResourceGraphDatasource(instanceSettings);
  42. this.resourcePickerData = new ResourcePickerData(instanceSettings);
  43. this.pseudoDatasource = {
  44. [AzureQueryType.AzureMonitor]: this.azureMonitorDatasource,
  45. [AzureQueryType.LogAnalytics]: this.azureLogAnalyticsDatasource,
  46. [AzureQueryType.AzureResourceGraph]: this.azureResourceGraphDatasource,
  47. };
  48. this.variables = new VariableSupport(this);
  49. }
  50. filterQuery(item: AzureMonitorQuery): boolean {
  51. if (!item.queryType) {
  52. return true;
  53. }
  54. const ds = this.pseudoDatasource[item.queryType];
  55. return ds?.filterQuery?.(item) ?? true;
  56. }
  57. query(options: DataQueryRequest<AzureMonitorQuery>): Observable<DataQueryResponse> {
  58. const byType = new Map<AzureQueryType, DataQueryRequest<AzureMonitorQuery>>();
  59. for (const baseTarget of options.targets) {
  60. // Migrate old query structures
  61. const target = datasourceMigrations(baseTarget, this.templateSrv);
  62. // Skip hidden or invalid queries or ones without properties
  63. if (!target.queryType || target.hide || !hasQueryForType(target)) {
  64. continue;
  65. }
  66. // Initialize the list of queries
  67. if (!byType.has(target.queryType)) {
  68. const queryForType = cloneDeep(options);
  69. queryForType.requestId = `${queryForType.requestId}-${target.refId}`;
  70. queryForType.targets = [];
  71. byType.set(target.queryType, queryForType);
  72. }
  73. const queryForType = byType.get(target.queryType);
  74. queryForType?.targets.push(target);
  75. }
  76. const observables: Array<Observable<DataQueryResponse>> = Array.from(byType.entries()).map(([queryType, req]) => {
  77. const ds = this.pseudoDatasource[queryType];
  78. if (!ds) {
  79. throw new Error('Data source not created for query type ' + queryType);
  80. }
  81. return ds.query(req);
  82. });
  83. // Single query can skip merge
  84. if (observables.length === 1) {
  85. return observables[0];
  86. }
  87. if (observables.length > 1) {
  88. return forkJoin(observables).pipe(
  89. map((results: DataQueryResponse[]) => {
  90. const data: DataFrame[] = [];
  91. for (const result of results) {
  92. for (const frame of result.data) {
  93. data.push(frame);
  94. }
  95. }
  96. return { state: LoadingState.Done, data };
  97. })
  98. );
  99. }
  100. return of({ state: LoadingState.Done, data: [] });
  101. }
  102. targetContainsTemplate(query: AzureMonitorQuery) {
  103. if (query.subscription && this.templateSrv.containsTemplate(query.subscription)) {
  104. return true;
  105. }
  106. let subQuery;
  107. if (query.queryType === AzureQueryType.AzureMonitor) {
  108. subQuery = JSON.stringify(query.azureMonitor);
  109. } else if (query.queryType === AzureQueryType.LogAnalytics) {
  110. subQuery = JSON.stringify(query.azureLogAnalytics);
  111. } else if (query.queryType === AzureQueryType.AzureResourceGraph) {
  112. subQuery = JSON.stringify([query.azureResourceGraph, query.subscriptions]);
  113. }
  114. return !!subQuery && this.templateSrv.containsTemplate(subQuery);
  115. }
  116. async annotationQuery(options: any) {
  117. return this.azureLogAnalyticsDatasource.annotationQuery(options);
  118. }
  119. async testDatasource(): Promise<DatasourceValidationResult> {
  120. const promises: Array<Promise<DatasourceValidationResult>> = [];
  121. promises.push(this.azureMonitorDatasource.testDatasource());
  122. promises.push(this.azureLogAnalyticsDatasource.testDatasource());
  123. return await Promise.all(promises).then((results) => {
  124. let status: 'success' | 'error' = 'success';
  125. let message = '';
  126. for (let i = 0; i < results.length; i++) {
  127. if (results[i].status !== 'success') {
  128. status = results[i].status;
  129. }
  130. message += `${i + 1}. ${results[i].message} `;
  131. }
  132. return {
  133. status: status,
  134. message: message,
  135. title: upperFirst(status),
  136. };
  137. });
  138. }
  139. /* Azure Monitor REST API methods */
  140. getResourceGroups(subscriptionId: string) {
  141. return this.azureMonitorDatasource.getResourceGroups(this.replaceTemplateVariable(subscriptionId));
  142. }
  143. getMetricDefinitions(subscriptionId: string, resourceGroup: string) {
  144. return this.azureMonitorDatasource.getMetricDefinitions(
  145. this.replaceTemplateVariable(subscriptionId),
  146. this.replaceTemplateVariable(resourceGroup)
  147. );
  148. }
  149. getResourceNames(subscriptionId: string, resourceGroup: string, metricDefinition: string) {
  150. return this.azureMonitorDatasource.getResourceNames(
  151. this.replaceTemplateVariable(subscriptionId),
  152. this.replaceTemplateVariable(resourceGroup),
  153. this.replaceTemplateVariable(metricDefinition)
  154. );
  155. }
  156. /*Azure Log Analytics */
  157. getAzureLogAnalyticsWorkspaces(subscriptionId: string) {
  158. return this.azureLogAnalyticsDatasource.getWorkspaces(subscriptionId);
  159. }
  160. getSubscriptions() {
  161. return this.azureMonitorDatasource.getSubscriptions();
  162. }
  163. interpolateVariablesInQueries(queries: AzureMonitorQuery[], scopedVars: ScopedVars): AzureMonitorQuery[] {
  164. const mapped = queries.map((query) => {
  165. if (!query.queryType) {
  166. return query;
  167. }
  168. const ds = this.pseudoDatasource[query.queryType];
  169. return {
  170. datasource: ds?.getRef(),
  171. ...(ds?.applyTemplateVariables(query, scopedVars) ?? query),
  172. };
  173. });
  174. return mapped;
  175. }
  176. replaceTemplateVariable(variable: string) {
  177. return this.templateSrv.replace(variable);
  178. }
  179. getVariables() {
  180. return this.templateSrv.getVariables().map((v) => `$${v.name}`);
  181. }
  182. isTemplateVariable(value: string) {
  183. return this.getVariables().includes(value);
  184. }
  185. }
  186. function hasQueryForType(query: AzureMonitorQuery): boolean {
  187. switch (query.queryType) {
  188. case AzureQueryType.AzureMonitor:
  189. return !!query.azureMonitor;
  190. case AzureQueryType.LogAnalytics:
  191. return !!query.azureLogAnalytics;
  192. case AzureQueryType.AzureResourceGraph:
  193. return !!query.azureResourceGraph;
  194. case AzureQueryType.GrafanaTemplateVariableFn:
  195. return !!query.grafanaTemplateVariableFn;
  196. default:
  197. return false;
  198. }
  199. }