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

[Ingest] Support yaml variables in datasource #64459

Merged
20 changes: 6 additions & 14 deletions x-pack/plugins/ingest_manager/server/services/datasource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
* you may not use this file except in compliance with the Elastic License.
*/
import { SavedObjectsClientContract } from 'src/core/server';
import { safeLoad } from 'js-yaml';
import { AuthenticatedUser } from '../../../security/server';
import {
DeleteDatasourcesResponse,
Expand Down Expand Up @@ -239,20 +238,13 @@ async function _assignPackageStreamToStream(
throw new Error(`Stream template not found for dataset ${dataset}`);
}

// Populate template variables from input config and stream config
const data: { [k: string]: string | string[] } = {};
if (input.vars) {
for (const key of Object.keys(input.vars)) {
data[key] = input.vars[key].value;
}
}
if (stream.vars) {
for (const key of Object.keys(stream.vars)) {
data[key] = stream.vars[key].value;
}
}
const yaml = safeLoad(createStream(data, pkgStream.buffer.toString()));
const yaml = createStream(
// Populate template variables from input vars and stream vars
Object.assign({}, input.vars, stream.vars),
pkgStream.buffer.toString()
);
stream.agent_stream = yaml;

return { ...stream };
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,29 +6,61 @@

import { createStream } from './agent';

test('Test creating a stream from template', () => {
const streamTemplate = `
input: log
paths:
{{#each paths}}
- {{this}}
{{/each}}
exclude_files: [".gz$"]
processors:
- add_locale: ~
`;
const vars = {
paths: ['/usr/local/var/log/nginx/access.log'],
};
describe('createStream', () => {
it('should work', () => {
const streamTemplate = `
input: log
paths:
{{#each paths}}
- {{this}}
{{/each}}
exclude_files: [".gz$"]
processors:
- add_locale: ~
`;
const vars = {
paths: { value: ['/usr/local/var/log/nginx/access.log'] },
};

const output = createStream(vars, streamTemplate);
const output = createStream(vars, streamTemplate);
expect(output).toEqual({
input: 'log',
paths: ['/usr/local/var/log/nginx/access.log'],
exclude_files: ['.gz$'],
processors: [{ add_locale: null }],
});
});

expect(output).toBe(`
input: log
paths:
- /usr/local/var/log/nginx/access.log
exclude_files: [".gz$"]
processors:
- add_locale: ~
`);
it('should support yaml values', () => {
Copy link
Contributor

Choose a reason for hiding this comment

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

If we changed createStream to accept a map of string -> any or unknown (vs current string -> string) I believe we could do this test like

test('Test nested', () => {
  const streamTemplate = `
host: {{host}}
{{#if key.patterns}}
key.patterns:{{key.patterns}}
{{/if}}
`;
  const vars = {
    host: 'http://127.0.0.1',
    key: {
      patterns: '\n  - limit: 20\n    pattern: .*',
    },
  };

  const output = createStream(vars, streamTemplate);

  expect(output).toBe(`
host: http://127.0.0.1
key.patterns:
  - limit: 20
    pattern: .*
`);
});

Copy link
Member Author

Choose a reason for hiding this comment

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

I could retranslate to a yaml after, but it's going to be stored as a JSON and send to the agent as a JSON, so if we can avoid one other round of conversion to yaml -> to json

const streamTemplate = `
input: redis/metrics
metricsets: ["key"]
test: null
{{#if key.patterns}}
key.patterns: {{key.patterns}}
{{/if}}
`;
const vars = {
'key.patterns': {
type: 'yaml',
value: `
- limit: 20
pattern: '*'
`,
},
};

const output = createStream(vars, streamTemplate);
expect(output).toEqual({
input: 'redis/metrics',
metricsets: ['key'],
test: null,
'key.patterns': [
{
limit: 20,
pattern: '*',
},
],
});
});
});
69 changes: 64 additions & 5 deletions x-pack/plugins/ingest_manager/server/services/epm/agent/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,71 @@
*/

import Handlebars from 'handlebars';
import { safeLoad } from 'js-yaml';
import { DatasourceConfigRecord } from '../../../../common';

interface StreamVars {
[k: string]: string | string[];
function isValidKey(key: string) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Not a blocker for this PR but future improvement: I think these services belong in /services/datasources.ts too rather than EPM as EPM services are registry & asset interactions. Might be good to make a separate directory for data source services as that single file is getting rather long.

return key !== '__proto__' && key !== 'constructor' && key !== 'prototype';
}

export function createStream(vars: StreamVars, streamTemplate: string) {
const template = Handlebars.compile(streamTemplate);
return template(vars);
function replaceVariablesInYaml(yamlVariables: { [k: string]: any }, yaml: any) {
if (Object.keys(yamlVariables).length === 0 || !yaml) {
return yaml;
}

Object.entries(yaml).forEach(([key, value]: [string, any]) => {
if (typeof value === 'object') {
yaml[key] = replaceVariablesInYaml(yamlVariables, value);
}
if (typeof value === 'string' && value in yamlVariables) {
yaml[key] = yamlVariables[value];
}
});

return yaml;
}

function buildTemplateVariables(variables: DatasourceConfigRecord) {
const yamlValues: { [k: string]: any } = {};
const vars = Object.entries(variables).reduce((acc, [key, recordEntry]) => {
// support variables with . like key.patterns
const keyParts = key.split('.');
const lastKeyPart = keyParts.pop();

if (!lastKeyPart || !isValidKey(lastKeyPart)) {
throw new Error('Invalid key');
}

let varPart = acc;
for (const keyPart of keyParts) {
if (!isValidKey(keyPart)) {
throw new Error('Invalid key');
}
if (!varPart[keyPart]) {
varPart[keyPart] = {};
}
varPart = varPart[keyPart];
}

if (recordEntry.type && recordEntry.type === 'yaml') {
const yamlKeyPlaceholder = `##${key}##`;
varPart[lastKeyPart] = `"${yamlKeyPlaceholder}"`;
nchaulet marked this conversation as resolved.
Show resolved Hide resolved
yamlValues[yamlKeyPlaceholder] = recordEntry.value ? safeLoad(recordEntry.value) : null;
} else {
varPart[lastKeyPart] = recordEntry.value;
}
return acc;
}, {} as { [k: string]: any });

return { vars, yamlValues };
}

export function createStream(variables: DatasourceConfigRecord, streamTemplate: string) {
const { vars, yamlValues } = buildTemplateVariables(variables);

const template = Handlebars.compile(streamTemplate, { noEscape: true });
nchaulet marked this conversation as resolved.
Show resolved Hide resolved
const stream = template(vars);
const yamlFromStream = safeLoad(stream, {});

return replaceVariablesInYaml(yamlValues, yamlFromStream);
}