Skip to content

Commit

Permalink
[Telemetry] Migrate ui_metric plugin to NP under usageCollecti… (#51972)
Browse files Browse the repository at this point in the history
* move cloud dir to plugins from legacy

* create ui_metrics in NP

* migrate first plugin

* ui_metric plugin uses npStart

* sinin mock

* karma mocks

* type check fix

* rename old configs

* fix mocks and use configs

* use  fo debug

* ui_metric deprecation configs

* remove commented out code

* remove unused type import

* mock ui_metric in client_integration

* jest.mock ui/new_platform

* fix all failing tests

* platform team code review fixes

* reset interval back to default

* apm cypress config use usageCollection

* revert kibana.yml change

* remove license type from NP def

* undo revert of NP type

* code review fixes

* report schema in a separate dir
  • Loading branch information
Bamieh authored Dec 13, 2019
1 parent 0dac435 commit 3658220
Show file tree
Hide file tree
Showing 46 changed files with 566 additions and 336 deletions.
1 change: 1 addition & 0 deletions packages/kbn-analytics/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,4 @@
export { ReportHTTP, Reporter, ReporterConfig } from './reporter';
export { UiStatsMetricType, METRIC_TYPE } from './metrics';
export { Report, ReportManager } from './report';
export { Storage } from './storage';
44 changes: 25 additions & 19 deletions packages/kbn-analytics/src/report.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,23 +23,25 @@ const REPORT_VERSION = 1;

export interface Report {
reportVersion: typeof REPORT_VERSION;
uiStatsMetrics: {
[key: string]: {
uiStatsMetrics?: Record<
string,
{
key: string;
appName: string;
eventName: string;
type: UiStatsMetricType;
stats: Stats;
};
};
userAgent?: {
[key: string]: {
}
>;
userAgent?: Record<
string,
{
userAgent: string;
key: string;
type: METRIC_TYPE.USER_AGENT;
appName: string;
};
};
}
>;
}

export class ReportManager {
Expand All @@ -49,14 +51,15 @@ export class ReportManager {
this.report = report || ReportManager.createReport();
}
static createReport(): Report {
return { reportVersion: REPORT_VERSION, uiStatsMetrics: {} };
return { reportVersion: REPORT_VERSION };
}
public clearReport() {
this.report = ReportManager.createReport();
}
public isReportEmpty(): boolean {
const noUiStats = Object.keys(this.report.uiStatsMetrics).length === 0;
const noUserAgent = !this.report.userAgent || Object.keys(this.report.userAgent).length === 0;
const { uiStatsMetrics, userAgent } = this.report;
const noUiStats = !uiStatsMetrics || Object.keys(uiStatsMetrics).length === 0;
const noUserAgent = !userAgent || Object.keys(userAgent).length === 0;
return noUiStats && noUserAgent;
}
private incrementStats(count: number, stats?: Stats): Stats {
Expand Down Expand Up @@ -113,14 +116,17 @@ export class ReportManager {
case METRIC_TYPE.LOADED:
case METRIC_TYPE.COUNT: {
const { appName, type, eventName, count } = metric;
const existingStats = (report.uiStatsMetrics[key] || {}).stats;
this.report.uiStatsMetrics[key] = {
key,
appName,
eventName,
type,
stats: this.incrementStats(count, existingStats),
};
if (report.uiStatsMetrics) {
const existingStats = (report.uiStatsMetrics[key] || {}).stats;
this.report.uiStatsMetrics = this.report.uiStatsMetrics || {};
this.report.uiStatsMetrics[key] = {
key,
appName,
eventName,
type,
stats: this.incrementStats(count, existingStats),
};
}
return;
}
default:
Expand Down
8 changes: 7 additions & 1 deletion packages/kbn-analytics/src/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,13 @@

import { Report } from './report';

export type Storage = Map<string, any>;
export interface Storage<T = any, S = void> {
get: (key: string) => T | null;
set: (key: string, value: T) => S;
remove: (key: string) => T | null;
clear: () => void;
}

export class ReportStorageManager {
storageKey: string;
private storage?: Storage;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { mountWithIntl } from 'test_utils/enzyme_helpers';
import { VisType } from '../legacy_imports';
import { TypesStart } from '../../../../visualizations/public/np_ready/public/types';

jest.mock('ui/new_platform');
jest.mock('../legacy_imports', () => ({
State: () => null,
AppState: () => null,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
*/

import moment from 'moment';
import { setCanTrackUiMetrics } from 'ui/ui_metric';
// @ts-ignore
import { banners, toastNotifications } from 'ui/notify';
import { npStart } from 'ui/new_platform';
Expand Down Expand Up @@ -69,8 +68,6 @@ export function TelemetryOptInProvider($injector: any, chrome: any, sendOptInSta
'telemetryNotifyUserAboutOptInDefault'
) as boolean;

setCanTrackUiMetrics(currentOptInStatus);

const provider = {
getBannerId: () => bannerId,
getOptInBannerNoticeId: () => optInBannerNoticeId,
Expand Down Expand Up @@ -116,7 +113,6 @@ export function TelemetryOptInProvider($injector: any, chrome: any, sendOptInSta
if (!allowChangingOptInStatus) {
return;
}
setCanTrackUiMetrics(enabled);
const $http = $injector.get('$http');

try {
Expand Down
78 changes: 0 additions & 78 deletions src/legacy/core_plugins/ui_metric/README.md

This file was deleted.

24 changes: 6 additions & 18 deletions src/legacy/core_plugins/ui_metric/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,36 +18,24 @@
*/

import { resolve } from 'path';
import JoiNamespace from 'joi';
import { Server } from 'hapi';
import { Legacy } from '../../../../kibana';
import { registerUiMetricRoute } from './server/routes/api/ui_metric';

// eslint-disable-next-line import/no-default-export
export default function(kibana: any) {
return new kibana.Plugin({
id: 'ui_metric',
require: ['kibana', 'elasticsearch'],
publicDir: resolve(__dirname, 'public'),
config(Joi: typeof JoiNamespace) {
return Joi.object({
enabled: Joi.boolean().default(true),
debug: Joi.boolean().default(Joi.ref('$dev')),
}).default();
},
uiExports: {
injectDefaultVars(server: Server) {
const config = server.config();
return {
uiMetricEnabled: config.get('ui_metric.enabled'),
debugUiMetric: config.get('ui_metric.debug'),
};
},
mappings: require('./mappings.json'),
hacks: ['plugins/ui_metric/hacks/ui_metric_init'],
},
init(server: Legacy.Server) {
registerUiMetricRoute(server);
const { getSavedObjectsRepository } = server.savedObjects;
const { callWithInternalUser } = server.plugins.elasticsearch.getCluster('admin');
const internalRepository = getSavedObjectsRepository(callWithInternalUser);
const { usageCollection } = server.newPlatform.setup.plugins;

usageCollection.registerLegacySavedObjects(internalRepository);
},
});
}
2 changes: 1 addition & 1 deletion src/legacy/core_plugins/ui_metric/public/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,5 @@
* under the License.
*/

export { createUiStatsReporter, trackUserAgent } from './services/telemetry_analytics';
export { createUiStatsReporter } from './services/telemetry_analytics';
export { METRIC_TYPE, UiStatsMetricType } from '@kbn/analytics';
Original file line number Diff line number Diff line change
Expand Up @@ -16,61 +16,9 @@
* specific language governing permissions and limitations
* under the License.
*/
import { npSetup } from 'ui/new_platform';

import { Reporter, UiStatsMetricType } from '@kbn/analytics';
// @ts-ignore
import { addSystemApiHeader } from 'ui/system_api';

let telemetryReporter: Reporter;

export const setTelemetryReporter = (aTelemetryReporter: Reporter): void => {
telemetryReporter = aTelemetryReporter;
};

export const getTelemetryReporter = () => {
return telemetryReporter;
};

export const createUiStatsReporter = (appName: string) => (
type: UiStatsMetricType,
eventNames: string | string[],
count?: number
): void => {
if (telemetryReporter) {
return telemetryReporter.reportUiStats(appName, type, eventNames, count);
}
export const createUiStatsReporter = (appName: string) => {
const { usageCollection } = npSetup.plugins;
return usageCollection.reportUiStats.bind(usageCollection, appName);
};

export const trackUserAgent = (appName: string) => {
if (telemetryReporter) {
return telemetryReporter.reportUserAgent(appName);
}
};

interface AnalyicsReporterConfig {
localStorage: any;
debug: boolean;
kfetch: any;
}

export function createAnalyticsReporter(config: AnalyicsReporterConfig) {
const { localStorage, debug, kfetch } = config;

return new Reporter({
debug,
storage: localStorage,
async http(report) {
const response = await kfetch({
method: 'POST',
pathname: '/api/telemetry/report',
body: JSON.stringify(report),
headers: addSystemApiHeader({}),
});

if (response.status !== 'ok') {
throw Error('Unable to store report.');
}
return response;
},
});
}
Loading

0 comments on commit 3658220

Please sign in to comment.