"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.JavaRuntimeAttachment = JavaRuntimeAttachment;
var _jsYaml = _interopRequireDefault(require("js-yaml"));
var _i18n = require("@kbn/i18n");
var _i18nReact = require("@kbn/i18n-react");
var _react = _interopRequireWildcard(require("react"));
var _ = require("..");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0; you may not use this file except in compliance with the Elastic License
 * 2.0.
 */

const DEFAULT_AGENT_VERSION = 'latest';
const excludeOptions = [{
  value: 'main',
  label: _i18n.i18n.translate('xpack.apm.fleetIntegration.javaRuntime.operationType.exclude.options.main', {
    defaultMessage: 'main'
  }),
  description: _i18n.i18n.translate('xpack.apm.fleetIntegration.javaRuntime.operationType.exclude.options.mainDescription', {
    defaultMessage: 'A regular expression of fully qualified main class names or paths to JARs of applications the java agent should be attached to. Performs a partial match so that foo matches /bin/foo.jar.'
  })
}, {
  value: 'vmarg',
  label: _i18n.i18n.translate('xpack.apm.fleetIntegration.javaRuntime.operationType.exclude.options.vmarg', {
    defaultMessage: 'vmarg'
  }),
  description: _i18n.i18n.translate('xpack.apm.fleetIntegration.javaRuntime.operationType.exclude.options.vmargDescription', {
    defaultMessage: 'A regular expression matched against the arguments passed to the JVM, such as system properties. Performs a partial match so that attach=true matches the system property -Dattach=true.'
  })
}, {
  value: 'user',
  label: _i18n.i18n.translate('xpack.apm.fleetIntegration.javaRuntime.operationType.exclude.options.user', {
    defaultMessage: 'user'
  }),
  description: _i18n.i18n.translate('xpack.apm.fleetIntegration.javaRuntime.operationType.exclude.options.userDescription', {
    defaultMessage: 'A username that is matched against the operating system user that runs the JVM.'
  })
}];
const includeOptions = [{
  value: 'all',
  label: _i18n.i18n.translate('xpack.apm.fleetIntegration.javaRuntime.operationType.include.options.all', {
    defaultMessage: 'All'
  }),
  description: _i18n.i18n.translate('xpack.apm.fleetIntegration.javaRuntime.operationType.include.options.allDescription', {
    defaultMessage: 'Includes all JVMs for attachment.'
  })
}, ...excludeOptions];
function getApmVars(newPolicy) {
  var _newPolicy$inputs$fin;
  return (_newPolicy$inputs$fin = newPolicy.inputs.find(({
    type
  }) => type === 'apm')) === null || _newPolicy$inputs$fin === void 0 ? void 0 : _newPolicy$inputs$fin.vars;
}
function JavaRuntimeAttachment({
  newPolicy,
  onChange
}) {
  var _apmVars$java_attache, _apmVars$java_attache2, _apmVars$java_attache3, _apmVars$java_attache4;
  const [isDirty, setIsDirty] = (0, _react.useState)(false);
  const onChangePolicy = (0, _react.useCallback)(runtimeAttachmentSettings => {
    const apmInputIdx = newPolicy.inputs.findIndex(({
      type
    }) => type === 'apm');
    onChange({
      isValid: !runtimeAttachmentSettings.enabled || (0, _.validateVersion)(runtimeAttachmentSettings.version),
      updatedPolicy: {
        ...newPolicy,
        inputs: [...newPolicy.inputs.slice(0, apmInputIdx), {
          ...newPolicy.inputs[apmInputIdx],
          vars: {
            ...newPolicy.inputs[apmInputIdx].vars,
            java_attacher_enabled: {
              value: runtimeAttachmentSettings.enabled,
              type: 'bool'
            },
            java_attacher_discovery_rules: {
              type: 'yaml',
              value: encodeDiscoveryRulesYaml(runtimeAttachmentSettings.discoveryRules)
            },
            java_attacher_agent_version: {
              type: 'text',
              value: runtimeAttachmentSettings.version
            }
          }
        }, ...newPolicy.inputs.slice(apmInputIdx + 1)]
      }
    });
    setIsDirty(true);
  }, [newPolicy, onChange]);
  function invalidatePackagePolicy() {
    onChange({
      isValid: false,
      updatedPolicy: newPolicy
    });
  }
  const apmVars = (0, _react.useMemo)(() => getApmVars(newPolicy), [newPolicy]);
  return /*#__PURE__*/_react.default.createElement(_.RuntimeAttachment, {
    operationTypes: [{
      operation: {
        value: 'include',
        label: _i18n.i18n.translate('xpack.apm.fleetIntegration.javaRuntime.operationType.include', {
          defaultMessage: 'Include'
        })
      },
      types: includeOptions
    }, {
      operation: {
        value: 'exclude',
        label: _i18n.i18n.translate('xpack.apm.fleetIntegration.javaRuntime.operationType.exclude', {
          defaultMessage: 'Exclude'
        })
      },
      types: excludeOptions
    }],
    onChange: onChangePolicy,
    toggleDescription: _i18n.i18n.translate('xpack.apm.fleetIntegration.javaRuntime.toggleDescription', {
      defaultMessage: 'Attach the Java agent to running and starting Java applications.'
    }),
    discoveryRulesDescription: /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "xpack.apm.fleetIntegration.javaRuntime.discoveryRulesDescription",
      defaultMessage: "For every running JVM, the discovery rules are evaluated in the order they are provided. The first matching rule determines the outcome. Learn more in the {docLink}.",
      values: {
        docLink: /*#__PURE__*/_react.default.createElement("a", {
          href: "https://www.elastic.co/guide/en/apm/agent/java/current/setup-attach-cli.html",
          target: "_blank"
        }, _i18n.i18n.translate('xpack.apm.fleetIntegration.javaRuntime.discoveryRulesDescription.docLink', {
          defaultMessage: 'docs'
        }))
      }
    }),
    showUnsavedWarning: isDirty,
    initialIsEnabled: apmVars === null || apmVars === void 0 ? void 0 : (_apmVars$java_attache = apmVars.java_attacher_enabled) === null || _apmVars$java_attache === void 0 ? void 0 : _apmVars$java_attache.value,
    initialDiscoveryRules: decodeDiscoveryRulesYaml((_apmVars$java_attache2 = apmVars === null || apmVars === void 0 ? void 0 : (_apmVars$java_attache3 = apmVars.java_attacher_discovery_rules) === null || _apmVars$java_attache3 === void 0 ? void 0 : _apmVars$java_attache3.value) !== null && _apmVars$java_attache2 !== void 0 ? _apmVars$java_attache2 : '[]\n', [initialDiscoveryRule]),
    version: (apmVars === null || apmVars === void 0 ? void 0 : (_apmVars$java_attache4 = apmVars.java_attacher_agent_version) === null || _apmVars$java_attache4 === void 0 ? void 0 : _apmVars$java_attache4.value) || DEFAULT_AGENT_VERSION,
    invalidatePackagePolicy: invalidatePackagePolicy
  });
}
const initialDiscoveryRule = {
  operation: 'include',
  type: 'vmarg',
  probe: 'elastic.apm.attach=true'
};
function decodeDiscoveryRulesYaml(discoveryRulesYaml, defaultDiscoveryRules = []) {
  try {
    var _yaml$load;
    const parsedYaml = (_yaml$load = _jsYaml.default.load(discoveryRulesYaml)) !== null && _yaml$load !== void 0 ? _yaml$load : [];
    if (parsedYaml.length === 0) {
      return defaultDiscoveryRules;
    }

    // transform into array of discovery rules
    return parsedYaml.map(discoveryRuleMap => {
      const [operationType, probe] = Object.entries(discoveryRuleMap)[0];
      return {
        operation: operationType.split('-')[0],
        type: operationType.split('-')[1],
        probe
      };
    });
  } catch (error) {
    return defaultDiscoveryRules;
  }
}
function encodeDiscoveryRulesYaml(discoveryRules) {
  // transform into list of key,value objects for expected yaml result
  const mappedDiscoveryRules = discoveryRules.map(({
    operation,
    type,
    probe
  }) => ({
    [`${operation}-${type}`]: probe
  }));
  return _jsYaml.default.dump(mappedDiscoveryRules);
}