From ad5c0f58fe2eac946a21a23f56f51cea74d1ab6b Mon Sep 17 00:00:00 2001 From: Jen Huang Date: Wed, 19 Aug 2020 13:52:06 -0700 Subject: [PATCH] [Ingest Manager] Rename agent/package config(s) to agent/package policy(ies) (#74914) * Initial pass at updating client routes, variables names, code comments, and UI copy * Adjust server routes and param names, more var names and i18n fixes * Fix test * More var renaming * Rest of server-side var renaming * Rest of client side var renaming * Rename agent SO attributes and add migrations * Remove agent prefix from policy fields * Rename agent policy SO attributes and add migrations * Rename enrollment api key SO attributes and add migrations * Rename package policy SO attributes and add migrations * Rename agent event SO attributes and add migrations * Rename subtype CONFIG to POLICY (I don't think this string is ever sent by agent, though) * Update snapshot * Remove unnecessary cloning in migrations * Fix migration typos * Update naming in tests and es archiver data * Rename file names in /common * Rename /server files * Rename /public files * Rename test file names * Rename missed files * Revert "Rename subtype CONFIG to POLICY (I don't think this string is ever sent by agent, though)" This reverts commit 3c91e01ed98d34de18a06ae8cb06dadf3b2c77be. * Add migration version to updated es archiver data to fix tests --- x-pack/plugins/ingest_manager/README.md | 2 +- .../ingest_manager/common/constants/agent.ts | 4 +- .../common/constants/agent_config.ts | 20 - .../common/constants/agent_policy.ts | 20 + .../ingest_manager/common/constants/index.ts | 4 +- .../{package_config.ts => package_policy.ts} | 2 +- .../ingest_manager/common/constants/routes.ts | 38 +- x-pack/plugins/ingest_manager/common/mocks.ts | 12 +- .../common/openapi/spec_oas3.json | 176 +++---- ...o_yaml.ts => full_agent_policy_to_yaml.ts} | 12 +- .../ingest_manager/common/services/index.ts | 8 +- .../common/services/limited_package.ts | 14 +- ... package_policies_to_agent_inputs.test.ts} | 38 +- ...ts => package_policies_to_agent_inputs.ts} | 32 +- ...t.ts => package_to_package_policy.test.ts} | 56 +-- ...config.ts => package_to_package_policy.ts} | 64 +-- .../ingest_manager/common/services/routes.ts | 52 +-- .../ingest_manager/common/types/index.ts | 4 +- .../common/types/models/agent.ts | 6 +- .../{agent_config.ts => agent_policy.ts} | 26 +- .../common/types/models/enrollment_api_key.ts | 12 +- .../common/types/models/index.ts | 4 +- .../common/types/models/package_config.ts | 73 --- .../common/types/models/package_policy.ts | 73 +++ .../common/types/rest_spec/agent.ts | 4 +- .../common/types/rest_spec/agent_config.ts | 83 ---- .../common/types/rest_spec/agent_policy.ts | 83 ++++ .../types/rest_spec/enrollment_api_key.ts | 2 +- .../common/types/rest_spec/index.ts | 4 +- .../common/types/rest_spec/package_config.ts | 59 --- .../common/types/rest_spec/package_policy.ts | 59 +++ .../dev_docs/actions_and_events.md | 2 +- .../dev_docs/api/agents_enroll.md | 2 +- .../ingest_manager/dev_docs/definitions.md | 21 +- x-pack/plugins/ingest_manager/dev_docs/epm.md | 22 +- .../fleet_agents_interactions_detailed.md | 14 +- .../dev_docs/schema/agent_checkin.mml | 6 +- .../dev_docs/schema/saved_objects.mml | 26 +- .../tutorial_directory_notice.tsx | 2 +- .../tutorial_module_notice.tsx | 2 +- .../components/settings_flyout.tsx | 4 +- .../ingest_manager/constants/index.ts | 4 +- .../ingest_manager/constants/page_paths.ts | 38 +- .../ingest_manager/hooks/use_breadcrumbs.tsx | 54 +-- .../hooks/use_request/agent_config.ts | 109 ----- .../hooks/use_request/agent_policy.ts | 109 +++++ .../ingest_manager/hooks/use_request/index.ts | 4 +- .../hooks/use_request/package_config.ts | 62 --- .../hooks/use_request/package_policy.ts | 62 +++ .../applications/ingest_manager/index.tsx | 8 +- .../ingest_manager/layouts/default.tsx | 9 +- .../sections/agent_config/components/index.ts | 12 - .../components/custom_package_config.tsx | 61 --- .../details_page/components/index.ts | 8 - .../components/package_configs/index.tsx | 23 - .../sections/agent_config/index.tsx | 36 -- .../components/actions_menu.tsx | 44 +- .../agent_policy_copy_provider.tsx} | 94 ++-- .../agent_policy_delete_provider.tsx} | 82 ++-- .../components/agent_policy_form.tsx} | 126 +++-- .../components/agent_policy_yaml_flyout.tsx} | 38 +- .../components/confirm_deploy_modal.tsx | 26 +- .../danger_eui_context_menu_item.tsx | 0 .../sections/agent_policy/components/index.ts | 14 + .../components/linked_agent_count.tsx | 8 +- .../package_policy_delete_provider.tsx} | 82 ++-- .../components/custom_package_policy.tsx | 61 +++ .../components/index.ts | 8 +- .../components/layout.tsx | 44 +- .../package_policy_input_config.tsx} | 42 +- .../package_policy_input_panel.tsx} | 82 ++-- .../package_policy_input_stream.tsx} | 42 +- .../package_policy_input_var_field.tsx} | 4 +- .../create_package_policy_page}/index.tsx | 244 +++++----- .../has_invalid_but_required_var.test.ts | 0 .../services/has_invalid_but_required_var.ts | 14 +- .../services/index.ts | 12 +- .../services/is_advanced_var.test.ts | 0 .../services/is_advanced_var.ts | 0 .../validate_package_policy.test..ts} | 56 +-- .../services/validate_package_policy.ts} | 74 +-- .../step_configure_package.tsx | 52 +-- .../step_define_package_policy.tsx} | 94 ++-- .../step_select_agent_policy.tsx} | 202 ++++---- .../step_select_package.tsx | 58 +-- .../create_package_policy_page}/types.ts | 4 +- .../details_page/components/index.ts | 8 + .../components/package_policies/index.tsx | 23 + .../package_policies/no_package_policies.tsx} | 12 +- .../package_policies_table.tsx} | 116 ++--- .../components/settings/index.tsx | 80 ++-- .../details_page/hooks/index.ts | 2 +- .../details_page/hooks/use_agent_status.tsx | 4 +- .../details_page/hooks/use_config.tsx | 6 +- .../details_page/index.tsx | 134 +++--- .../edit_package_policy_page}/index.tsx | 220 ++++----- .../sections/agent_policy/index.tsx | 36 ++ .../components/create_agent_policy.tsx} | 64 +-- .../list_page/components/index.ts | 2 +- .../list_page/index.tsx | 151 +++--- .../sections/data_stream/list_page/index.tsx | 2 +- .../ingest_manager/sections/epm/index.tsx | 6 +- .../detail/confirm_package_uninstall.tsx | 2 +- .../sections/epm/screens/detail/content.tsx | 4 +- .../sections/epm/screens/detail/index.tsx | 4 +- ...s_panel.tsx => package_policies_panel.tsx} | 4 +- .../epm/screens/detail/settings_panel.tsx | 14 +- .../epm/screens/detail/side_nav_links.tsx | 2 +- .../components/actions_menu.tsx | 8 +- .../components/agent_details.tsx | 18 +- .../components/type_labels.tsx | 4 +- .../fleet/agent_details_page/index.tsx | 40 +- .../sections/fleet/agent_list_page/index.tsx | 126 ++--- ...lection.tsx => agent_policy_selection.tsx} | 82 ++-- .../agent_enrollment_flyout/index.tsx | 10 +- .../managed_instructions.tsx | 10 +- .../standalone_instructions.tsx | 48 +- .../agent_enrollment_flyout/steps.tsx | 24 +- ...es.tsx => agent_policy_package_badges.tsx} | 32 +- .../index.tsx | 63 +-- .../sections/fleet/components/index.tsx | 2 +- .../sections/fleet/components/list_layout.tsx | 12 +- .../components/new_enrollment_key_flyout.tsx | 33 +- .../enrollment_token_list_page/index.tsx | 20 +- .../sections/fleet/setup_page/index.tsx | 4 +- .../ingest_manager/sections/index.tsx | 4 +- ...n_section.tsx => agent_policy_section.tsx} | 36 +- .../overview/components/agent_section.tsx | 2 +- .../components/integration_section.tsx | 2 +- .../sections/overview/index.tsx | 16 +- .../ingest_manager/services/index.ts | 12 +- .../ingest_manager/types/index.ts | 56 +-- .../types/intra_app_route_state.ts | 24 +- x-pack/plugins/ingest_manager/public/index.ts | 10 +- .../plugins/ingest_manager/public/plugin.ts | 6 +- .../server/collectors/agent_collectors.ts | 4 +- .../server/collectors/package_collectors.ts | 23 +- .../ingest_manager/server/constants/index.ts | 14 +- x-pack/plugins/ingest_manager/server/index.ts | 14 +- .../server/integration_tests/router.test.ts | 42 +- x-pack/plugins/ingest_manager/server/mocks.ts | 8 +- .../plugins/ingest_manager/server/plugin.ts | 30 +- .../server/routes/agent/handlers.ts | 11 +- .../server/routes/agent/index.ts | 6 +- .../server/routes/agent_config/index.ts | 108 ----- .../handlers.ts | 174 +++---- .../server/routes/agent_policy/index.ts | 108 +++++ .../routes/enrollment_api_key/handler.ts | 2 +- .../ingest_manager/server/routes/index.ts | 4 +- .../server/routes/package_config/index.ts | 73 --- .../handlers.test.ts | 56 +-- .../handlers.ts | 90 ++-- .../server/routes/package_policy/index.ts | 73 +++ .../server/saved_objects/index.ts | 53 ++- .../saved_objects/migrations/to_v7_10_0.ts | 72 +++ .../server/services/agent_config.ts | 442 ------------------ ...nt_config.test.ts => agent_policy.test.ts} | 34 +- .../server/services/agent_policy.ts | 442 ++++++++++++++++++ ...onfig_update.ts => agent_policy_update.ts} | 14 +- .../server/services/agents/acks.test.ts | 16 +- .../server/services/agents/acks.ts | 20 +- .../server/services/agents/checkin/index.ts | 2 +- .../agents/checkin/state_new_actions.ts | 78 ++-- .../server/services/agents/enroll.ts | 6 +- .../server/services/agents/reassign.ts | 14 +- .../server/services/agents/status.ts | 18 +- .../server/services/agents/update.ts | 7 +- .../services/api_keys/enrollment_api_key.ts | 25 +- .../server/services/api_keys/index.ts | 6 +- .../ingest_manager/server/services/config.ts | 2 +- .../server/services/epm/agent/agent.ts | 6 +- .../server/services/epm/packages/get.ts | 2 +- .../server/services/epm/packages/remove.ts | 10 +- .../ingest_manager/server/services/index.ts | 4 +- ..._config.test.ts => package_policy.test.ts} | 22 +- .../{package_config.ts => package_policy.ts} | 218 ++++----- .../ingest_manager/server/services/setup.ts | 62 +-- .../ingest_manager/server/types/index.tsx | 28 +- .../server/types/models/agent.ts | 2 +- .../{agent_config.ts => agent_policy.ts} | 22 +- .../server/types/models/enrollment_api_key.ts | 12 +- .../server/types/models/index.ts | 4 +- .../{package_config.ts => package_policy.ts} | 16 +- .../server/types/rest_spec/agent.ts | 4 +- .../{agent_config.ts => agent_policy.ts} | 30 +- .../types/rest_spec/enrollment_api_key.ts | 2 +- .../server/types/rest_spec/index.ts | 4 +- .../server/types/rest_spec/package_config.ts | 33 -- .../server/types/rest_spec/package_policy.ts | 33 ++ .../common/endpoint/generate_data.ts | 20 +- .../common/endpoint/types.ts | 8 +- .../use_navigate_to_app_event_handler.ts | 4 +- .../mock/endpoint/dependencies_start_mock.ts | 4 +- .../pages/endpoint_hosts/store/middleware.ts | 24 +- .../store/mock_endpoint_result_list.ts | 30 +- .../view/details/endpoint_details.tsx | 4 +- .../pages/endpoint_hosts/view/index.test.tsx | 12 +- .../pages/endpoint_hosts/view/index.tsx | 14 +- .../policy/store/policy_details/index.test.ts | 4 +- .../policy/store/policy_details/middleware.ts | 22 +- .../policy/store/policy_details/selectors.ts | 2 +- .../pages/policy/store/policy_list/action.ts | 2 +- .../policy/store/policy_list/index.test.ts | 28 +- .../policy/store/policy_list/middleware.ts | 22 +- .../store/policy_list/services/ingest.test.ts | 30 +- .../store/policy_list/services/ingest.ts | 82 ++-- .../store/policy_list/test_mock_utils.ts | 6 +- .../public/management/pages/policy/types.ts | 16 +- ...onfig.tsx => configure_package_policy.tsx} | 36 +- .../pages/policy/view/policy_details.test.tsx | 24 +- .../pages/policy/view/policy_details.tsx | 2 +- .../pages/policy/view/policy_list.test.tsx | 2 +- .../pages/policy/view/policy_list.tsx | 26 +- .../security_solution/public/plugin.tsx | 6 +- .../endpoint/endpoint_app_context_services.ts | 6 +- .../endpoint/ingest_integration.test.ts | 20 +- .../server/endpoint/ingest_integration.ts | 30 +- .../server/endpoint/lib/artifacts/mocks.ts | 20 +- .../server/endpoint/lib/artifacts/task.ts | 2 +- .../server/endpoint/mocks.ts | 4 +- .../manifest_manager/manifest_manager.mock.ts | 26 +- .../manifest_manager/manifest_manager.test.ts | 20 +- .../manifest_manager/manifest_manager.ts | 30 +- .../security_solution/server/plugin.ts | 2 +- .../server/usage/endpoints/endpoint.mocks.ts | 10 +- .../translations/translations/ja-JP.json | 410 ++++++++-------- .../translations/translations/zh-CN.json | 410 ++++++++-------- .../endpoint/artifacts/api_feature/data.json | 14 +- .../es_archives/fleet/agents/data.json | 35 +- .../es_archives/fleet/agents/mappings.json | 15 +- .../es_archives/lists/mappings.json | 12 +- .../canvas_disallowed_url/mappings.json | 12 +- .../agent_policy.ts} | 34 +- .../{agent_config => agent_policy}/index.js | 2 +- .../apis/fleet/agents/complete_flow.ts | 6 +- .../apis/fleet/agents/enroll.ts | 2 +- .../apis/fleet/enrollment_api_keys/crud.ts | 14 +- .../apis/index.js | 13 +- .../create.ts | 40 +- .../{package_config => package_policy}/get.ts | 34 +- .../update.ts | 42 +- .../es_archives/export_rule/mappings.json | 10 +- .../apps/endpoint/endpoint_list.ts | 2 +- .../apps/endpoint/policy_details.ts | 48 +- .../apps/endpoint/policy_list.ts | 42 +- .../page_objects/index.ts | 4 +- ...est_manager_create_package_policy_page.ts} | 50 +- .../page_objects/policy_page.ts | 6 +- .../services/endpoint_policy.ts | 150 +++--- 249 files changed, 4845 insertions(+), 4720 deletions(-) delete mode 100644 x-pack/plugins/ingest_manager/common/constants/agent_config.ts create mode 100644 x-pack/plugins/ingest_manager/common/constants/agent_policy.ts rename x-pack/plugins/ingest_manager/common/constants/{package_config.ts => package_policy.ts} (79%) rename x-pack/plugins/ingest_manager/common/services/{config_to_yaml.ts => full_agent_policy_to_yaml.ts} (70%) rename x-pack/plugins/ingest_manager/common/services/{package_configs_to_agent_inputs.test.ts => package_policies_to_agent_inputs.test.ts} (80%) rename x-pack/plugins/ingest_manager/common/services/{package_configs_to_agent_inputs.ts => package_policies_to_agent_inputs.ts} (62%) rename x-pack/plugins/ingest_manager/common/services/{package_to_config.test.ts => package_to_package_policy.test.ts} (88%) rename x-pack/plugins/ingest_manager/common/services/{package_to_config.ts => package_to_package_policy.ts} (65%) rename x-pack/plugins/ingest_manager/common/types/models/{agent_config.ts => agent_policy.ts} (65%) delete mode 100644 x-pack/plugins/ingest_manager/common/types/models/package_config.ts create mode 100644 x-pack/plugins/ingest_manager/common/types/models/package_policy.ts delete mode 100644 x-pack/plugins/ingest_manager/common/types/rest_spec/agent_config.ts create mode 100644 x-pack/plugins/ingest_manager/common/types/rest_spec/agent_policy.ts delete mode 100644 x-pack/plugins/ingest_manager/common/types/rest_spec/package_config.ts create mode 100644 x-pack/plugins/ingest_manager/common/types/rest_spec/package_policy.ts delete mode 100644 x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_request/agent_config.ts create mode 100644 x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_request/agent_policy.ts delete mode 100644 x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_request/package_config.ts create mode 100644 x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_request/package_policy.ts delete mode 100644 x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/index.ts delete mode 100644 x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/components/custom_package_config.tsx delete mode 100644 x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/index.ts delete mode 100644 x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/package_configs/index.tsx delete mode 100644 x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/index.tsx rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config => agent_policy}/components/actions_menu.tsx (74%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config/components/config_copy_provider.tsx => agent_policy/components/agent_policy_copy_provider.tsx} (54%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config/components/config_delete_provider.tsx => agent_policy/components/agent_policy_delete_provider.tsx} (62%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config/components/config_form.tsx => agent_policy/components/agent_policy_form.tsx} (70%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config/components/config_yaml_flyout.tsx => agent_policy/components/agent_policy_yaml_flyout.tsx} (68%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config => agent_policy}/components/confirm_deploy_modal.tsx (72%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config => agent_policy}/components/danger_eui_context_menu_item.tsx (100%) create mode 100644 x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/components/index.ts rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config => agent_policy}/components/linked_agent_count.tsx (77%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config/components/package_config_delete_provider.tsx => agent_policy/components/package_policy_delete_provider.tsx} (70%) create mode 100644 x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/components/custom_package_policy.tsx rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config/create_package_config_page => agent_policy/create_package_policy_page}/components/index.ts (51%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config/create_package_config_page => agent_policy/create_package_policy_page}/components/layout.tsx (79%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config/create_package_config_page/components/package_config_input_config.tsx => agent_policy/create_package_policy_page/components/package_policy_input_config.tsx} (83%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config/create_package_config_page/components/package_config_input_panel.tsx => agent_policy/create_package_policy_page/components/package_policy_input_panel.tsx} (74%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config/create_package_config_page/components/package_config_input_stream.tsx => agent_policy/create_package_policy_page/components/package_policy_input_stream.tsx} (83%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config/create_package_config_page/components/package_config_input_var_field.tsx => agent_policy/create_package_policy_page/components/package_policy_input_var_field.tsx} (95%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config/create_package_config_page => agent_policy/create_package_policy_page}/index.tsx (60%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config/create_package_config_page => agent_policy/create_package_policy_page}/services/has_invalid_but_required_var.test.ts (100%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config/create_package_config_page => agent_policy/create_package_policy_page}/services/has_invalid_but_required_var.ts (60%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config/create_package_config_page => agent_policy/create_package_policy_page}/services/index.ts (67%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config/create_package_config_page => agent_policy/create_package_policy_page}/services/is_advanced_var.test.ts (100%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config/create_package_config_page => agent_policy/create_package_policy_page}/services/is_advanced_var.ts (100%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config/create_package_config_page/services/validate_package_config.ts.test.ts => agent_policy/create_package_policy_page/services/validate_package_policy.test..ts} (91%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config/create_package_config_page/services/validate_package_config.ts => agent_policy/create_package_policy_page/services/validate_package_policy.ts} (76%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config/create_package_config_page => agent_policy/create_package_policy_page}/step_configure_package.tsx (68%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config/create_package_config_page/step_define_package_config.tsx => agent_policy/create_package_policy_page/step_define_package_policy.tsx} (64%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config/create_package_config_page/step_select_config.tsx => agent_policy/create_package_policy_page/step_select_agent_policy.tsx} (51%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config/create_package_config_page => agent_policy/create_package_policy_page}/step_select_package.tsx (80%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config/create_package_config_page => agent_policy/create_package_policy_page}/types.ts (68%) create mode 100644 x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/details_page/components/index.ts create mode 100644 x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/details_page/components/package_policies/index.tsx rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config/details_page/components/package_configs/no_package_configs.tsx => agent_policy/details_page/components/package_policies/no_package_policies.tsx} (68%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config/details_page/components/package_configs/package_configs_table.tsx => agent_policy/details_page/components/package_policies/package_policies_table.tsx} (62%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config => agent_policy}/details_page/components/settings/index.tsx (73%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config => agent_policy}/details_page/hooks/index.ts (80%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config => agent_policy}/details_page/hooks/use_agent_status.tsx (93%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config => agent_policy}/details_page/hooks/use_config.tsx (59%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config => agent_policy}/details_page/index.tsx (64%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config/edit_package_config_page => agent_policy/edit_package_policy_page}/index.tsx (59%) create mode 100644 x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/index.tsx rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config/list_page/components/create_config.tsx => agent_policy/list_page/components/create_agent_policy.tsx} (65%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config => agent_policy}/list_page/components/index.ts (78%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/{agent_config => agent_policy}/list_page/index.tsx (61%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/{package_configs_panel.tsx => package_policies_panel.tsx} (88%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/{config_selection.tsx => agent_policy_selection.tsx} (67%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/{agent_config_package_badges.tsx => agent_policy_package_badges.tsx} (52%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/{agent_reassign_config_flyout => agent_reassign_policy_flyout}/index.tsx (63%) rename x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/{configuration_section.tsx => agent_policy_section.tsx} (61%) delete mode 100644 x-pack/plugins/ingest_manager/server/routes/agent_config/index.ts rename x-pack/plugins/ingest_manager/server/routes/{agent_config => agent_policy}/handlers.ts (54%) create mode 100644 x-pack/plugins/ingest_manager/server/routes/agent_policy/index.ts delete mode 100644 x-pack/plugins/ingest_manager/server/routes/package_config/index.ts rename x-pack/plugins/ingest_manager/server/routes/{package_config => package_policy}/handlers.test.ts (83%) rename x-pack/plugins/ingest_manager/server/routes/{package_config => package_policy}/handlers.ts (61%) create mode 100644 x-pack/plugins/ingest_manager/server/routes/package_policy/index.ts create mode 100644 x-pack/plugins/ingest_manager/server/saved_objects/migrations/to_v7_10_0.ts delete mode 100644 x-pack/plugins/ingest_manager/server/services/agent_config.ts rename x-pack/plugins/ingest_manager/server/services/{agent_config.test.ts => agent_policy.test.ts} (74%) create mode 100644 x-pack/plugins/ingest_manager/server/services/agent_policy.ts rename x-pack/plugins/ingest_manager/server/services/{agent_config_update.ts => agent_policy_update.ts} (64%) rename x-pack/plugins/ingest_manager/server/services/{package_config.test.ts => package_policy.test.ts} (88%) rename x-pack/plugins/ingest_manager/server/services/{package_config.ts => package_policy.ts} (58%) rename x-pack/plugins/ingest_manager/server/types/models/{agent_config.ts => agent_policy.ts} (60%) rename x-pack/plugins/ingest_manager/server/types/models/{package_config.ts => package_policy.ts} (85%) rename x-pack/plugins/ingest_manager/server/types/rest_spec/{agent_config.ts => agent_policy.ts} (58%) delete mode 100644 x-pack/plugins/ingest_manager/server/types/rest_spec/package_config.ts create mode 100644 x-pack/plugins/ingest_manager/server/types/rest_spec/package_policy.ts rename x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/{configure_package_config.tsx => configure_package_policy.tsx} (73%) rename x-pack/test/ingest_manager_api_integration/apis/{agent_config/agent_config.ts => agent_policy/agent_policy.ts} (71%) rename x-pack/test/ingest_manager_api_integration/apis/{agent_config => agent_policy}/index.js (86%) rename x-pack/test/ingest_manager_api_integration/apis/{package_config => package_policy}/create.ts (81%) rename x-pack/test/ingest_manager_api_integration/apis/{package_config => package_policy}/get.ts (68%) rename x-pack/test/ingest_manager_api_integration/apis/{package_config => package_policy}/update.ts (72%) rename x-pack/test/security_solution_endpoint/page_objects/{ingest_manager_create_package_config_page.ts => ingest_manager_create_package_policy_page.ts} (56%) diff --git a/x-pack/plugins/ingest_manager/README.md b/x-pack/plugins/ingest_manager/README.md index 9fd23e3d41ddec..a95a2582f1f600 100644 --- a/x-pack/plugins/ingest_manager/README.md +++ b/x-pack/plugins/ingest_manager/README.md @@ -3,7 +3,7 @@ ## Plugin - The plugin is enabled by default. See the TypeScript type for the [the available plugin configuration options](https://github.com/elastic/kibana/blob/master/x-pack/plugins/ingest_manager/common/types/index.ts#L9-L27) -- Adding `xpack.ingestManager.enabled=false` will disable the plugin including the EPM and Fleet features. It will also remove the `PACKAGE_CONFIG_API_ROUTES` and `AGENT_CONFIG_API_ROUTES` values in [`common/constants/routes.ts`](./common/constants/routes.ts) +- Adding `xpack.ingestManager.enabled=false` will disable the plugin including the EPM and Fleet features. It will also remove the `PACKAGE_POLICY_API_ROUTES` and `AGENT_POLICY_API_ROUTES` values in [`common/constants/routes.ts`](./common/constants/routes.ts) - Adding `--xpack.ingestManager.fleet.enabled=false` will disable the Fleet API & UI - [code for adding the routes](https://github.com/elastic/kibana/blob/1f27d349533b1c2865c10c45b2cf705d7416fb36/x-pack/plugins/ingest_manager/server/plugin.ts#L115-L133) - [Integration tests](server/integration_tests/router.test.ts) diff --git a/x-pack/plugins/ingest_manager/common/constants/agent.ts b/x-pack/plugins/ingest_manager/common/constants/agent.ts index d94f536b5659a6..6d0d9ee801a941 100644 --- a/x-pack/plugins/ingest_manager/common/constants/agent.ts +++ b/x-pack/plugins/ingest_manager/common/constants/agent.ts @@ -17,5 +17,5 @@ export const AGENT_POLLING_INTERVAL = 1000; export const AGENT_UPDATE_LAST_CHECKIN_INTERVAL_MS = 30000; export const AGENT_UPDATE_ACTIONS_INTERVAL_MS = 5000; -export const AGENT_CONFIG_ROLLOUT_RATE_LIMIT_INTERVAL_MS = 5000; -export const AGENT_CONFIG_ROLLOUT_RATE_LIMIT_REQUEST_PER_INTERVAL = 25; +export const AGENT_POLICY_ROLLOUT_RATE_LIMIT_INTERVAL_MS = 5000; +export const AGENT_POLICY_ROLLOUT_RATE_LIMIT_REQUEST_PER_INTERVAL = 25; diff --git a/x-pack/plugins/ingest_manager/common/constants/agent_config.ts b/x-pack/plugins/ingest_manager/common/constants/agent_config.ts deleted file mode 100644 index aa6399b73f14ed..00000000000000 --- a/x-pack/plugins/ingest_manager/common/constants/agent_config.ts +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -import { AgentConfigStatus, DefaultPackages } from '../types'; - -export const AGENT_CONFIG_SAVED_OBJECT_TYPE = 'ingest-agent-policies'; - -export const DEFAULT_AGENT_CONFIG = { - name: 'Default config', - namespace: 'default', - description: 'Default agent configuration created by Kibana', - status: AgentConfigStatus.Active, - package_configs: [], - is_default: true, - monitoring_enabled: ['logs', 'metrics'] as Array<'logs' | 'metrics'>, -}; - -export const DEFAULT_AGENT_CONFIGS_PACKAGES = [DefaultPackages.system]; diff --git a/x-pack/plugins/ingest_manager/common/constants/agent_policy.ts b/x-pack/plugins/ingest_manager/common/constants/agent_policy.ts new file mode 100644 index 00000000000000..f6261790f66739 --- /dev/null +++ b/x-pack/plugins/ingest_manager/common/constants/agent_policy.ts @@ -0,0 +1,20 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { AgentPolicyStatus, DefaultPackages } from '../types'; + +export const AGENT_POLICY_SAVED_OBJECT_TYPE = 'ingest-agent-policies'; + +export const DEFAULT_AGENT_POLICY = { + name: 'Default policy', + namespace: 'default', + description: 'Default agent policy created by Kibana', + status: AgentPolicyStatus.Active, + package_policies: [], + is_default: true, + monitoring_enabled: ['logs', 'metrics'] as Array<'logs' | 'metrics'>, +}; + +export const DEFAULT_AGENT_POLICIES_PACKAGES = [DefaultPackages.system]; diff --git a/x-pack/plugins/ingest_manager/common/constants/index.ts b/x-pack/plugins/ingest_manager/common/constants/index.ts index ed01fcdd316a32..519e2861cdc1d4 100644 --- a/x-pack/plugins/ingest_manager/common/constants/index.ts +++ b/x-pack/plugins/ingest_manager/common/constants/index.ts @@ -7,8 +7,8 @@ export * from './plugin'; export * from './routes'; export * from './agent'; -export * from './agent_config'; -export * from './package_config'; +export * from './agent_policy'; +export * from './package_policy'; export * from './epm'; export * from './output'; export * from './enrollment_api_key'; diff --git a/x-pack/plugins/ingest_manager/common/constants/package_config.ts b/x-pack/plugins/ingest_manager/common/constants/package_policy.ts similarity index 79% rename from x-pack/plugins/ingest_manager/common/constants/package_config.ts rename to x-pack/plugins/ingest_manager/common/constants/package_policy.ts index 48fee967a3d3d6..27814e6baafb16 100644 --- a/x-pack/plugins/ingest_manager/common/constants/package_config.ts +++ b/x-pack/plugins/ingest_manager/common/constants/package_policy.ts @@ -4,4 +4,4 @@ * you may not use this file except in compliance with the Elastic License. */ -export const PACKAGE_CONFIG_SAVED_OBJECT_TYPE = 'ingest-package-policies'; +export const PACKAGE_POLICY_SAVED_OBJECT_TYPE = 'ingest-package-policies'; diff --git a/x-pack/plugins/ingest_manager/common/constants/routes.ts b/x-pack/plugins/ingest_manager/common/constants/routes.ts index 94265c3920922c..551a0f7d601643 100644 --- a/x-pack/plugins/ingest_manager/common/constants/routes.ts +++ b/x-pack/plugins/ingest_manager/common/constants/routes.ts @@ -7,8 +7,8 @@ export const API_ROOT = `/api/ingest_manager`; export const EPM_API_ROOT = `${API_ROOT}/epm`; export const DATA_STREAM_API_ROOT = `${API_ROOT}/data_streams`; -export const PACKAGE_CONFIG_API_ROOT = `${API_ROOT}/package_configs`; -export const AGENT_CONFIG_API_ROOT = `${API_ROOT}/agent_configs`; +export const PACKAGE_POLICY_API_ROOT = `${API_ROOT}/package_policies`; +export const AGENT_POLICY_API_ROOT = `${API_ROOT}/agent_policies`; export const FLEET_API_ROOT = `${API_ROOT}/fleet`; export const LIMITED_CONCURRENCY_ROUTE_TAG = 'ingest:limited-concurrency'; @@ -32,25 +32,25 @@ export const DATA_STREAM_API_ROUTES = { LIST_PATTERN: `${DATA_STREAM_API_ROOT}`, }; -// Package config API routes -export const PACKAGE_CONFIG_API_ROUTES = { - LIST_PATTERN: `${PACKAGE_CONFIG_API_ROOT}`, - INFO_PATTERN: `${PACKAGE_CONFIG_API_ROOT}/{packageConfigId}`, - CREATE_PATTERN: `${PACKAGE_CONFIG_API_ROOT}`, - UPDATE_PATTERN: `${PACKAGE_CONFIG_API_ROOT}/{packageConfigId}`, - DELETE_PATTERN: `${PACKAGE_CONFIG_API_ROOT}/delete`, +// Package policy API routes +export const PACKAGE_POLICY_API_ROUTES = { + LIST_PATTERN: `${PACKAGE_POLICY_API_ROOT}`, + INFO_PATTERN: `${PACKAGE_POLICY_API_ROOT}/{packagePolicyId}`, + CREATE_PATTERN: `${PACKAGE_POLICY_API_ROOT}`, + UPDATE_PATTERN: `${PACKAGE_POLICY_API_ROOT}/{packagePolicyId}`, + DELETE_PATTERN: `${PACKAGE_POLICY_API_ROOT}/delete`, }; -// Agent config API routes -export const AGENT_CONFIG_API_ROUTES = { - LIST_PATTERN: `${AGENT_CONFIG_API_ROOT}`, - INFO_PATTERN: `${AGENT_CONFIG_API_ROOT}/{agentConfigId}`, - CREATE_PATTERN: `${AGENT_CONFIG_API_ROOT}`, - UPDATE_PATTERN: `${AGENT_CONFIG_API_ROOT}/{agentConfigId}`, - COPY_PATTERN: `${AGENT_CONFIG_API_ROOT}/{agentConfigId}/copy`, - DELETE_PATTERN: `${AGENT_CONFIG_API_ROOT}/delete`, - FULL_INFO_PATTERN: `${AGENT_CONFIG_API_ROOT}/{agentConfigId}/full`, - FULL_INFO_DOWNLOAD_PATTERN: `${AGENT_CONFIG_API_ROOT}/{agentConfigId}/download`, +// Agent policy API routes +export const AGENT_POLICY_API_ROUTES = { + LIST_PATTERN: `${AGENT_POLICY_API_ROOT}`, + INFO_PATTERN: `${AGENT_POLICY_API_ROOT}/{agentPolicyId}`, + CREATE_PATTERN: `${AGENT_POLICY_API_ROOT}`, + UPDATE_PATTERN: `${AGENT_POLICY_API_ROOT}/{agentPolicyId}`, + COPY_PATTERN: `${AGENT_POLICY_API_ROOT}/{agentPolicyId}/copy`, + DELETE_PATTERN: `${AGENT_POLICY_API_ROOT}/delete`, + FULL_INFO_PATTERN: `${AGENT_POLICY_API_ROOT}/{agentPolicyId}/full`, + FULL_INFO_DOWNLOAD_PATTERN: `${AGENT_POLICY_API_ROOT}/{agentPolicyId}/download`, }; // Output API routes diff --git a/x-pack/plugins/ingest_manager/common/mocks.ts b/x-pack/plugins/ingest_manager/common/mocks.ts index e85364f2bb672b..1e14245e0f3ef5 100644 --- a/x-pack/plugins/ingest_manager/common/mocks.ts +++ b/x-pack/plugins/ingest_manager/common/mocks.ts @@ -4,15 +4,15 @@ * you may not use this file except in compliance with the Elastic License. */ -import { NewPackageConfig, PackageConfig } from './types/models/package_config'; +import { NewPackagePolicy, PackagePolicy } from './types'; -export const createNewPackageConfigMock = (): NewPackageConfig => { +export const createNewPackagePolicyMock = (): NewPackagePolicy => { return { name: 'endpoint-1', description: '', namespace: 'default', enabled: true, - config_id: '93c46720-c217-11ea-9906-b5b8a21b268e', + policy_id: '93c46720-c217-11ea-9906-b5b8a21b268e', output_id: '', package: { name: 'endpoint', @@ -23,10 +23,10 @@ export const createNewPackageConfigMock = (): NewPackageConfig => { }; }; -export const createPackageConfigMock = (): PackageConfig => { - const newPackageConfig = createNewPackageConfigMock(); +export const createPackagePolicyMock = (): PackagePolicy => { + const newPackagePolicy = createNewPackagePolicyMock(); return { - ...newPackageConfig, + ...newPackagePolicy, id: 'c6d16e42-c32d-4dce-8a88-113cfe276ad1', version: 'abcd', revision: 1, diff --git a/x-pack/plugins/ingest_manager/common/openapi/spec_oas3.json b/x-pack/plugins/ingest_manager/common/openapi/spec_oas3.json index cfae2c450c824e..8c9ede1fde9ba1 100644 --- a/x-pack/plugins/ingest_manager/common/openapi/spec_oas3.json +++ b/x-pack/plugins/ingest_manager/common/openapi/spec_oas3.json @@ -17,9 +17,9 @@ } ], "paths": { - "/agent_configs": { + "/agent_policies": { "get": { - "summary": "Agent Config - List", + "summary": "Agent policy - List", "tags": [], "responses": { "200": { @@ -32,7 +32,7 @@ "items": { "type": "array", "items": { - "$ref": "#/components/schemas/AgentConfig" + "$ref": "#/components/schemas/AgentPolicy" } }, "total": { @@ -56,11 +56,11 @@ "items": [ { "id": "82da1fc0-8fbf-11ea-b2ce-01c4a6127154", - "name": "Default config", + "name": "Default policy", "namespace": "default", - "description": "Default agent configuration created by Kibana", + "description": "Default agent policy created by Kibana", "status": "active", - "packageConfigs": ["8a5679b0-8fbf-11ea-b2ce-01c4a6127154"], + "packagePolicies": ["8a5679b0-8fbf-11ea-b2ce-01c4a6127154"], "is_default": true, "monitoring_enabled": ["logs", "metrics"], "revision": 2, @@ -80,7 +80,7 @@ } } }, - "operationId": "agent-config-list", + "operationId": "agent-policy-list", "parameters": [ { "$ref": "#/components/parameters/pageSizeParam" @@ -95,7 +95,7 @@ "description": "" }, "post": { - "summary": "Agent Config - Create", + "summary": "Agent policy - Create", "tags": [], "responses": { "200": { @@ -106,7 +106,7 @@ "type": "object", "properties": { "item": { - "$ref": "#/components/schemas/AgentConfig" + "$ref": "#/components/schemas/AgentPolicy" }, "success": { "type": "boolean" @@ -117,12 +117,12 @@ } } }, - "operationId": "post-agent_configs", + "operationId": "post-agent-policy", "requestBody": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/NewAgentConfig" + "$ref": "#/components/schemas/NewAgentPolicy" } } } @@ -135,19 +135,19 @@ ] } }, - "/agent_configs/{agentConfigId}": { + "/agent_policies/{agentPolicyId}": { "parameters": [ { "schema": { "type": "string" }, - "name": "agentConfigId", + "name": "agentPolicyId", "in": "path", "required": true } ], "get": { - "summary": "Agent Config - Info", + "summary": "Agent policy - Info", "tags": [], "responses": { "200": { @@ -158,7 +158,7 @@ "type": "object", "properties": { "item": { - "$ref": "#/components/schemas/AgentConfig" + "$ref": "#/components/schemas/AgentPolicy" }, "success": { "type": "boolean" @@ -171,11 +171,11 @@ "value": { "item": { "id": "82da1fc0-8fbf-11ea-b2ce-01c4a6127154", - "name": "Default config", + "name": "Default policy", "namespace": "default", - "description": "Default agent configuration created by Kibana", + "description": "Default agent policy created by Kibana", "status": "active", - "packageConfigs": [ + "packagePolicies": [ { "id": "8a5679b0-8fbf-11ea-b2ce-01c4a6127154", "name": "system-1", @@ -186,7 +186,7 @@ "version": "0.0.3" }, "enabled": true, - "config_id": "82da1fc0-8fbf-11ea-b2ce-01c4a6127154", + "policy_id": "82da1fc0-8fbf-11ea-b2ce-01c4a6127154", "output_id": "08adc51c-69f3-4294-80e2-24527c6ff73d", "inputs": [ { @@ -716,12 +716,12 @@ } } }, - "operationId": "agent-config-info", - "description": "Get one agent config", + "operationId": "agent-policy-info", + "description": "Get one agent policy", "parameters": [] }, "put": { - "summary": "Agent Config - Update", + "summary": "Agent policy - Update", "tags": [], "responses": { "200": { @@ -732,7 +732,7 @@ "type": "object", "properties": { "item": { - "$ref": "#/components/schemas/AgentConfig" + "$ref": "#/components/schemas/AgentPolicy" }, "success": { "type": "boolean" @@ -750,7 +750,7 @@ "namespace": "UPDATED namespace", "updated_on": "Fri Feb 28 2020 16:22:31 GMT-0500 (Eastern Standard Time)", "updated_by": "elastic", - "packageConfigs": [] + "packagePolicies": [] }, "success": true } @@ -760,12 +760,12 @@ } } }, - "operationId": "put-agent_configs-agentConfigId", + "operationId": "put-agent-policy-agentPolicyId", "requestBody": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/NewAgentConfig" + "$ref": "#/components/schemas/NewAgentPolicy" }, "examples": { "example-1": { @@ -786,20 +786,20 @@ ] } }, - "/agent_configs/{agentConfigId}/copy": { + "/agent_policies/{agentPolicyId}/copy": { "parameters": [ { "schema": { "type": "string" }, - "name": "agentConfigId", + "name": "agentPolicyId", "in": "path", "required": true } ], "post": { - "summary": "Agent config - copy one config", - "operationId": "agent-config-copy", + "summary": "Agent policy - copy one policy", + "operationId": "agent-policy-copy", "responses": { "200": { "description": "OK", @@ -809,7 +809,7 @@ "type": "object", "properties": { "item": { - "$ref": "#/components/schemas/AgentConfig" + "$ref": "#/components/schemas/AgentPolicy" }, "success": { "type": "boolean" @@ -841,13 +841,13 @@ }, "description": "" }, - "description": "Copies one agent config" + "description": "Copies one agent policy" } }, - "/agent_configs/delete": { + "/agent_policies/delete": { "post": { - "summary": "Agent Config - Delete", - "operationId": "post-agent_config-delete", + "summary": "Agent policy - Delete", + "operationId": "post-agent-policy-delete", "responses": { "200": { "description": "OK", @@ -896,7 +896,7 @@ "schema": { "type": "object", "properties": { - "agentConfigIds": { + "agentPolicyIds": { "type": "array", "items": { "type": "string" @@ -907,7 +907,7 @@ "examples": { "example-1": { "value": { - "agentConfigIds": ["df7d2540-5a47-11ea-80da-89b5a66da347"] + "agentPolicyIds": ["df7d2540-5a47-11ea-80da-89b5a66da347"] } } } @@ -922,9 +922,9 @@ }, "parameters": [] }, - "/package_configs": { + "/package_policies": { "get": { - "summary": "PackageConfigs - List", + "summary": "PackagePolicies - List", "tags": [], "responses": { "200": { @@ -937,7 +937,7 @@ "items": { "type": "array", "items": { - "$ref": "#/components/schemas/PackageConfig" + "$ref": "#/components/schemas/PackagePolicy" } }, "total": { @@ -1166,14 +1166,14 @@ } } }, - "operationId": "get-packageConfigs", + "operationId": "get-packagePolicies", "security": [], "parameters": [] }, "parameters": [], "post": { - "summary": "PackageConfigs - Create", - "operationId": "post-packageConfigs", + "summary": "PackagePolicies - Create", + "operationId": "post-packagePolicies", "responses": { "200": { "description": "OK" @@ -1183,7 +1183,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/NewPackageConfig" + "$ref": "#/components/schemas/NewPackagePolicy" }, "examples": { "example-1": { @@ -1237,9 +1237,9 @@ ] } }, - "/package_configs/{packageConfigId}": { + "/package_policies/{packagePolicyId}": { "get": { - "summary": "PackageConfigs - Info", + "summary": "PackagePolicies - Info", "tags": [], "responses": { "200": { @@ -1250,7 +1250,7 @@ "type": "object", "properties": { "item": { - "$ref": "#/components/schemas/PackageConfig" + "$ref": "#/components/schemas/PackagePolicy" }, "success": { "type": "boolean" @@ -1262,21 +1262,21 @@ } } }, - "operationId": "get-packageConfigs-packageConfigId" + "operationId": "get-packagePolicies-packagePolicyId" }, "parameters": [ { "schema": { "type": "string" }, - "name": "packageConfigId", + "name": "packagePolicyId", "in": "path", "required": true } ], "put": { - "summary": "PackageConfigs - Update", - "operationId": "put-packageConfigs-packageConfigId", + "summary": "PackagePolicies - Update", + "operationId": "put-packagePolicies-packagePolicyId", "responses": { "200": { "description": "OK", @@ -1286,7 +1286,7 @@ "type": "object", "properties": { "item": { - "$ref": "#/components/schemas/PackageConfig" + "$ref": "#/components/schemas/PackagePolicy" }, "sucess": { "type": "boolean" @@ -1824,10 +1824,10 @@ "path": "telemetry" } ], - "packageConfigs": [ + "packagePolicies": [ { "name": "endpoint", - "title": "Endpoint package config", + "title": "Endpoint package policy", "description": "Interact with the endpoint.", "inputs": null, "multiple": false @@ -2119,7 +2119,7 @@ } }, { - "description": "The log package should be used to create package configs for all type of logs for which an package doesn't exist yet.\n", + "description": "The log package should be used to create package policies for all type of logs for which an package doesn't exist yet.\n", "download": "/epr/log/log-0.9.0.tar.gz", "icons": [ { @@ -2765,7 +2765,7 @@ { "id": "205661d0-5e53-11ea-ad31-4f31c06bd9a4", "active": true, - "config_id": "ae556400-5e39-11ea-8b49-f9747e466f7b", + "policy_id": "ae556400-5e39-11ea-8b49-f9747e466f7b", "type": "PERMANENT", "enrolled_at": "2020-03-04T20:02:50.605Z", "user_provided_metadata": { @@ -2780,7 +2780,7 @@ }, "actions": [ { - "data": "{\"config\":{\"id\":\"ae556400-5e39-11ea-8b49-f9747e466f7b\",\"outputs\":{\"default\":{\"type\":\"elasticsearch\",\"hosts\":[\"http://localhost:9200\"],\"api_key\":\"\",\"api_token\":\"6ckkp3ABz7e_XRqr3LM8:gQuDfUNSRgmY0iziYqP9Hw\"}},\"packageConfigs\":[]}}", + "data": "{\"config\":{\"id\":\"ae556400-5e39-11ea-8b49-f9747e466f7b\",\"outputs\":{\"default\":{\"type\":\"elasticsearch\",\"hosts\":[\"http://localhost:9200\"],\"api_key\":\"\",\"api_token\":\"6ckkp3ABz7e_XRqr3LM8:gQuDfUNSRgmY0iziYqP9Hw\"}},\"packagePolicies\":[]}}", "created_at": "2020-03-04T20:02:56.149Z", "id": "6a95c00a-d76d-4931-97c3-0bf935272d7d", "type": "CONFIG_CHANGE" @@ -2965,7 +2965,7 @@ "api_key": "Z-XkgHIBvwtjzIKtSCTh:AejRqdKpQx6z-6dqSI1LHg" } }, - "packageConfigs": [ + "packagePolicies": [ { "id": "33d6bd70-a5e0-11ea-a587-5f886c8a849f", "name": "system-1", @@ -3433,7 +3433,7 @@ "item": { "id": "8086fb1a-72ca-4a67-8533-09300c1639fa", "active": true, - "config_id": "2fe89350-a5e0-11ea-a587-5f886c8a849f", + "policy_id": "2fe89350-a5e0-11ea-a587-5f886c8a849f", "type": "PERMANENT", "enrolled_at": "2020-06-04T13:03:57.856Z", "user_provided_metadata": { @@ -3562,22 +3562,22 @@ } } }, - "/fleet/config/{configId}/agent-status": { - "parameters": [ - { - "schema": { - "type": "string" - }, - "name": "configId", - "in": "path", - "required": true - } - ], + "/fleet/agent-status": { "get": { - "summary": "Fleet - Agent - Status for config", + "summary": "Fleet - Agent - Status for policy", "tags": [], "responses": {}, - "operationId": "get-fleet-config-configId-agent-status" + "operationId": "get-fleet-agent-status", + "parameters": [ + { + "schema": { + "type": "string" + }, + "name": "policyId", + "in": "query", + "required": false + } + ] } }, "/fleet/enrollment-api-keys": { @@ -3702,10 +3702,10 @@ }, "components": { "schemas": { - "AgentConfig": { + "AgentPolicy": { "allOf": [ { - "$ref": "#/components/schemas/NewAgentConfig" + "$ref": "#/components/schemas/NewAgentPolicy" }, { "type": "object", @@ -3717,7 +3717,7 @@ "type": "string", "enum": ["active", "inactive"] }, - "packageConfigs": { + "packagePolicies": { "oneOf": [ { "items": { @@ -3726,7 +3726,7 @@ }, { "items": { - "$ref": "#/components/schemas/PackageConfig" + "$ref": "#/components/schemas/PackagePolicy" } } ], @@ -3750,8 +3750,8 @@ } ] }, - "PackageConfig": { - "title": "PackageConfig", + "PackagePolicy": { + "title": "PackagePolicy", "allOf": [ { "type": "object", @@ -3770,15 +3770,15 @@ "required": ["id", "revision"] }, { - "$ref": "#/components/schemas/NewPackageConfig" + "$ref": "#/components/schemas/NewPackagePolicy" } ], "x-examples": { "example-1": {} } }, - "NewAgentConfig": { - "title": "NewAgentConfig", + "NewAgentPolicy": { + "title": "NewAgentPolicy", "type": "object", "properties": { "name": { @@ -3792,8 +3792,8 @@ } } }, - "NewPackageConfig": { - "title": "NewPackageConfig", + "NewPackagePolicy": { + "title": "NewPackagePolicy", "type": "object", "x-examples": { "example-1": { @@ -3892,7 +3892,7 @@ "required": ["type", "enabled", "streams"] } }, - "config_id": { + "policy_id": { "type": "string" }, "name": { @@ -3902,7 +3902,7 @@ "type": "string" } }, - "required": ["output_id", "inputs", "config_id", "name"] + "required": ["output_id", "inputs", "policy_id", "name"] }, "PackageInfo": { "title": "PackageInfo", @@ -4140,10 +4140,10 @@ "default_api_key_id": { "type": "string" }, - "config_id": { + "policy_id": { "type": "string" }, - "config_revision": { + "policy_revision": { "type": ["number", "null"] }, "last_checkin": { @@ -4221,7 +4221,7 @@ "agent_id": { "type": "string" }, - "config_id": { + "policy_id": { "type": "string" }, "stream_id": { diff --git a/x-pack/plugins/ingest_manager/common/services/config_to_yaml.ts b/x-pack/plugins/ingest_manager/common/services/full_agent_policy_to_yaml.ts similarity index 70% rename from x-pack/plugins/ingest_manager/common/services/config_to_yaml.ts rename to x-pack/plugins/ingest_manager/common/services/full_agent_policy_to_yaml.ts index e2e6393738d1f2..5b4a3b2dacf7b9 100644 --- a/x-pack/plugins/ingest_manager/common/services/config_to_yaml.ts +++ b/x-pack/plugins/ingest_manager/common/services/full_agent_policy_to_yaml.ts @@ -4,9 +4,9 @@ * you may not use this file except in compliance with the Elastic License. */ import { safeDump } from 'js-yaml'; -import { FullAgentConfig } from '../types'; +import { FullAgentPolicy } from '../types'; -const CONFIG_KEYS_ORDER = [ +const POLICY_KEYS_ORDER = [ 'id', 'name', 'revision', @@ -21,12 +21,12 @@ const CONFIG_KEYS_ORDER = [ 'input', ]; -export const configToYaml = (config: FullAgentConfig): string => { - return safeDump(config, { +export const fullAgentPolicyToYaml = (policy: FullAgentPolicy): string => { + return safeDump(policy, { skipInvalid: true, sortKeys: (keyA: string, keyB: string) => { - const indexA = CONFIG_KEYS_ORDER.indexOf(keyA); - const indexB = CONFIG_KEYS_ORDER.indexOf(keyB); + const indexA = POLICY_KEYS_ORDER.indexOf(keyA); + const indexB = POLICY_KEYS_ORDER.indexOf(keyB); if (indexA >= 0 && indexB < 0) { return -1; } diff --git a/x-pack/plugins/ingest_manager/common/services/index.ts b/x-pack/plugins/ingest_manager/common/services/index.ts index 0c91dbbe103545..28fd15b5ea7006 100644 --- a/x-pack/plugins/ingest_manager/common/services/index.ts +++ b/x-pack/plugins/ingest_manager/common/services/index.ts @@ -5,8 +5,8 @@ */ export * from './routes'; export * as AgentStatusKueryHelper from './agent_status'; -export { packageToPackageConfigInputs, packageToPackageConfig } from './package_to_config'; -export { storedPackageConfigsToAgentInputs } from './package_configs_to_agent_inputs'; -export { configToYaml } from './config_to_yaml'; -export { isPackageLimited, doesAgentConfigAlreadyIncludePackage } from './limited_package'; +export { packageToPackagePolicyInputs, packageToPackagePolicy } from './package_to_package_policy'; +export { storedPackagePoliciesToAgentInputs } from './package_policies_to_agent_inputs'; +export { fullAgentPolicyToYaml } from './full_agent_policy_to_yaml'; +export { isPackageLimited, doesAgentPolicyAlreadyIncludePackage } from './limited_package'; export { decodeCloudId } from './decode_cloud_id'; diff --git a/x-pack/plugins/ingest_manager/common/services/limited_package.ts b/x-pack/plugins/ingest_manager/common/services/limited_package.ts index 7ef445d55063c0..21d1dbd1556b7c 100644 --- a/x-pack/plugins/ingest_manager/common/services/limited_package.ts +++ b/x-pack/plugins/ingest_manager/common/services/limited_package.ts @@ -3,21 +3,21 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { PackageInfo, AgentConfig, PackageConfig } from '../types'; +import { PackageInfo, AgentPolicy, PackagePolicy } from '../types'; // Assume packages only ever include 1 config template for now export const isPackageLimited = (packageInfo: PackageInfo): boolean => { return packageInfo.config_templates?.[0]?.multiple === false; }; -export const doesAgentConfigAlreadyIncludePackage = ( - agentConfig: AgentConfig, +export const doesAgentPolicyAlreadyIncludePackage = ( + agentPolicy: AgentPolicy, packageName: string ): boolean => { - if (agentConfig.package_configs.length && typeof agentConfig.package_configs[0] === 'string') { - throw new Error('Unable to read full package config information'); + if (agentPolicy.package_policies.length && typeof agentPolicy.package_policies[0] === 'string') { + throw new Error('Unable to read full package policy information'); } - return (agentConfig.package_configs as PackageConfig[]) - .map((packageConfig) => packageConfig.package?.name || '') + return (agentPolicy.package_policies as PackagePolicy[]) + .map((packagePolicy) => packagePolicy.package?.name || '') .includes(packageName); }; diff --git a/x-pack/plugins/ingest_manager/common/services/package_configs_to_agent_inputs.test.ts b/x-pack/plugins/ingest_manager/common/services/package_policies_to_agent_inputs.test.ts similarity index 80% rename from x-pack/plugins/ingest_manager/common/services/package_configs_to_agent_inputs.test.ts rename to x-pack/plugins/ingest_manager/common/services/package_policies_to_agent_inputs.test.ts index d6c09f058ab85b..956423a4973731 100644 --- a/x-pack/plugins/ingest_manager/common/services/package_configs_to_agent_inputs.test.ts +++ b/x-pack/plugins/ingest_manager/common/services/package_policies_to_agent_inputs.test.ts @@ -3,19 +3,19 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { PackageConfig, PackageConfigInput } from '../types'; -import { storedPackageConfigsToAgentInputs } from './package_configs_to_agent_inputs'; +import { PackagePolicy, PackagePolicyInput } from '../types'; +import { storedPackagePoliciesToAgentInputs } from './package_policies_to_agent_inputs'; -describe('Ingest Manager - storedPackageConfigsToAgentInputs', () => { - const mockPackageConfig: PackageConfig = { +describe('Ingest Manager - storedPackagePoliciesToAgentInputs', () => { + const mockPackagePolicy: PackagePolicy = { id: 'some-uuid', - name: 'mock-package-config', + name: 'mock-package-policy', description: '', created_at: '', created_by: '', updated_at: '', updated_by: '', - config_id: '', + policy_id: '', enabled: true, output_id: '', namespace: 'default', @@ -23,7 +23,7 @@ describe('Ingest Manager - storedPackageConfigsToAgentInputs', () => { revision: 1, }; - const mockInput: PackageConfigInput = { + const mockInput: PackagePolicyInput = { type: 'test-logs', enabled: true, vars: { @@ -74,13 +74,13 @@ describe('Ingest Manager - storedPackageConfigsToAgentInputs', () => { ], }; - it('returns no inputs for package config with no inputs, or only disabled inputs', () => { - expect(storedPackageConfigsToAgentInputs([mockPackageConfig])).toEqual([]); + it('returns no inputs for package policy with no inputs, or only disabled inputs', () => { + expect(storedPackagePoliciesToAgentInputs([mockPackagePolicy])).toEqual([]); expect( - storedPackageConfigsToAgentInputs([ + storedPackagePoliciesToAgentInputs([ { - ...mockPackageConfig, + ...mockPackagePolicy, package: { name: 'mock-package', title: 'Mock package', @@ -91,9 +91,9 @@ describe('Ingest Manager - storedPackageConfigsToAgentInputs', () => { ).toEqual([]); expect( - storedPackageConfigsToAgentInputs([ + storedPackagePoliciesToAgentInputs([ { - ...mockPackageConfig, + ...mockPackagePolicy, inputs: [{ ...mockInput, enabled: false }], }, ]) @@ -102,9 +102,9 @@ describe('Ingest Manager - storedPackageConfigsToAgentInputs', () => { it('returns agent inputs', () => { expect( - storedPackageConfigsToAgentInputs([ + storedPackagePoliciesToAgentInputs([ { - ...mockPackageConfig, + ...mockPackagePolicy, package: { name: 'mock-package', title: 'Mock package', @@ -116,7 +116,7 @@ describe('Ingest Manager - storedPackageConfigsToAgentInputs', () => { ).toEqual([ { id: 'some-uuid', - name: 'mock-package-config', + name: 'mock-package-policy', type: 'test-logs', data_stream: { namespace: 'default' }, use_output: 'default', @@ -144,9 +144,9 @@ describe('Ingest Manager - storedPackageConfigsToAgentInputs', () => { it('returns agent inputs without disabled streams', () => { expect( - storedPackageConfigsToAgentInputs([ + storedPackagePoliciesToAgentInputs([ { - ...mockPackageConfig, + ...mockPackagePolicy, inputs: [ { ...mockInput, @@ -158,7 +158,7 @@ describe('Ingest Manager - storedPackageConfigsToAgentInputs', () => { ).toEqual([ { id: 'some-uuid', - name: 'mock-package-config', + name: 'mock-package-policy', type: 'test-logs', data_stream: { namespace: 'default' }, use_output: 'default', diff --git a/x-pack/plugins/ingest_manager/common/services/package_configs_to_agent_inputs.ts b/x-pack/plugins/ingest_manager/common/services/package_policies_to_agent_inputs.ts similarity index 62% rename from x-pack/plugins/ingest_manager/common/services/package_configs_to_agent_inputs.ts rename to x-pack/plugins/ingest_manager/common/services/package_policies_to_agent_inputs.ts index b94fc39e0567cc..639f20eb088281 100644 --- a/x-pack/plugins/ingest_manager/common/services/package_configs_to_agent_inputs.ts +++ b/x-pack/plugins/ingest_manager/common/services/package_policies_to_agent_inputs.ts @@ -3,29 +3,29 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { PackageConfig, FullAgentConfigInput, FullAgentConfigInputStream } from '../types'; +import { PackagePolicy, FullAgentPolicyInput, FullAgentPolicyInputStream } from '../types'; import { DEFAULT_OUTPUT } from '../constants'; -export const storedPackageConfigsToAgentInputs = ( - packageConfigs: PackageConfig[] -): FullAgentConfigInput[] => { - const fullInputs: FullAgentConfigInput[] = []; +export const storedPackagePoliciesToAgentInputs = ( + packagePolicies: PackagePolicy[] +): FullAgentPolicyInput[] => { + const fullInputs: FullAgentPolicyInput[] = []; - packageConfigs.forEach((packageConfig) => { - if (!packageConfig.enabled || !packageConfig.inputs || !packageConfig.inputs.length) { + packagePolicies.forEach((packagePolicy) => { + if (!packagePolicy.enabled || !packagePolicy.inputs || !packagePolicy.inputs.length) { return; } - packageConfig.inputs.forEach((input) => { + packagePolicy.inputs.forEach((input) => { if (!input.enabled) { return; } - const fullInput: FullAgentConfigInput = { - id: packageConfig.id || packageConfig.name, - name: packageConfig.name, + const fullInput: FullAgentPolicyInput = { + id: packagePolicy.id || packagePolicy.name, + name: packagePolicy.name, type: input.type, data_stream: { - namespace: packageConfig.namespace || 'default', + namespace: packagePolicy.namespace || 'default', }, use_output: DEFAULT_OUTPUT.name, ...Object.entries(input.config || {}).reduce((acc, [key, { value }]) => { @@ -35,7 +35,7 @@ export const storedPackageConfigsToAgentInputs = ( streams: input.streams .filter((stream) => stream.enabled) .map((stream) => { - const fullStream: FullAgentConfigInputStream = { + const fullStream: FullAgentPolicyInputStream = { id: stream.id, data_stream: stream.data_stream, ...stream.compiled_stream, @@ -48,11 +48,11 @@ export const storedPackageConfigsToAgentInputs = ( }), }; - if (packageConfig.package) { + if (packagePolicy.package) { fullInput.meta = { package: { - name: packageConfig.package.name, - version: packageConfig.package.version, + name: packagePolicy.package.name, + version: packagePolicy.package.version, }, }; } diff --git a/x-pack/plugins/ingest_manager/common/services/package_to_config.test.ts b/x-pack/plugins/ingest_manager/common/services/package_to_package_policy.test.ts similarity index 88% rename from x-pack/plugins/ingest_manager/common/services/package_to_config.test.ts rename to x-pack/plugins/ingest_manager/common/services/package_to_package_policy.test.ts index 1f4cd43247be17..6c3559d7cc5a03 100644 --- a/x-pack/plugins/ingest_manager/common/services/package_to_config.test.ts +++ b/x-pack/plugins/ingest_manager/common/services/package_to_package_policy.test.ts @@ -4,9 +4,9 @@ * you may not use this file except in compliance with the Elastic License. */ import { PackageInfo, InstallationStatus } from '../types'; -import { packageToPackageConfig, packageToPackageConfigInputs } from './package_to_config'; +import { packageToPackagePolicy, packageToPackagePolicyInputs } from './package_to_package_policy'; -describe('Ingest Manager - packageToConfig', () => { +describe('Ingest Manager - packageToPackagePolicy', () => { const mockPackage: PackageInfo = { name: 'mock-package', title: 'Mock package', @@ -31,15 +31,15 @@ describe('Ingest Manager - packageToConfig', () => { status: InstallationStatus.notInstalled, }; - describe('packageToPackageConfigInputs', () => { + describe('packageToPackagePolicyInputs', () => { it('returns empty array for packages with no config templates', () => { - expect(packageToPackageConfigInputs(mockPackage)).toEqual([]); - expect(packageToPackageConfigInputs({ ...mockPackage, config_templates: [] })).toEqual([]); + expect(packageToPackagePolicyInputs(mockPackage)).toEqual([]); + expect(packageToPackagePolicyInputs({ ...mockPackage, config_templates: [] })).toEqual([]); }); it('returns empty array for packages with a config template but no inputs', () => { expect( - packageToPackageConfigInputs(({ + packageToPackagePolicyInputs(({ ...mockPackage, config_templates: [{ inputs: [] }], } as unknown) as PackageInfo) @@ -48,13 +48,13 @@ describe('Ingest Manager - packageToConfig', () => { it('returns inputs with no streams for packages with no streams', () => { expect( - packageToPackageConfigInputs(({ + packageToPackagePolicyInputs(({ ...mockPackage, config_templates: [{ inputs: [{ type: 'foo' }] }], } as unknown) as PackageInfo) ).toEqual([{ type: 'foo', enabled: true, streams: [] }]); expect( - packageToPackageConfigInputs(({ + packageToPackagePolicyInputs(({ ...mockPackage, config_templates: [{ inputs: [{ type: 'foo' }, { type: 'bar' }] }], } as unknown) as PackageInfo) @@ -66,7 +66,7 @@ describe('Ingest Manager - packageToConfig', () => { it('returns inputs with streams for packages with streams', () => { expect( - packageToPackageConfigInputs(({ + packageToPackagePolicyInputs(({ ...mockPackage, datasets: [ { type: 'logs', name: 'foo', streams: [{ input: 'foo' }] }, @@ -100,7 +100,7 @@ describe('Ingest Manager - packageToConfig', () => { it('returns inputs with streams configurations for packages with stream vars', () => { expect( - packageToPackageConfigInputs(({ + packageToPackagePolicyInputs(({ ...mockPackage, datasets: [ { @@ -171,7 +171,7 @@ describe('Ingest Manager - packageToConfig', () => { it('returns inputs with streams configurations for packages with stream and input vars', () => { expect( - packageToPackageConfigInputs(({ + packageToPackagePolicyInputs(({ ...mockPackage, datasets: [ { @@ -315,10 +315,10 @@ describe('Ingest Manager - packageToConfig', () => { }); }); - describe('packageToPackageConfig', () => { - it('returns package config with default name', () => { - expect(packageToPackageConfig(mockPackage, '1', '2')).toEqual({ - config_id: '1', + describe('packageToPackagePolicy', () => { + it('returns package policy with default name', () => { + expect(packageToPackagePolicy(mockPackage, '1', '2')).toEqual({ + policy_id: '1', namespace: '', enabled: true, inputs: [], @@ -331,13 +331,13 @@ describe('Ingest Manager - packageToConfig', () => { }, }); }); - it('returns package config with custom name', () => { - expect(packageToPackageConfig(mockPackage, '1', '2', 'default', 'pkgConfig-1')).toEqual({ - config_id: '1', + it('returns package policy with custom name', () => { + expect(packageToPackagePolicy(mockPackage, '1', '2', 'default', 'pkgPolicy-1')).toEqual({ + policy_id: '1', namespace: 'default', enabled: true, inputs: [], - name: 'pkgConfig-1', + name: 'pkgPolicy-1', output_id: '2', package: { name: 'mock-package', @@ -346,21 +346,21 @@ describe('Ingest Manager - packageToConfig', () => { }, }); }); - it('returns package config with namespace and description', () => { + it('returns package policy with namespace and description', () => { expect( - packageToPackageConfig( + packageToPackagePolicy( mockPackage, '1', '2', 'mock-namespace', - 'pkgConfig-1', + 'pkgPolicy-1', 'Test description' ) ).toEqual({ - config_id: '1', + policy_id: '1', enabled: true, inputs: [], - name: 'pkgConfig-1', + name: 'pkgPolicy-1', namespace: 'mock-namespace', description: 'Test description', output_id: '2', @@ -371,20 +371,20 @@ describe('Ingest Manager - packageToConfig', () => { }, }); }); - it('returns package config with inputs', () => { + it('returns package policy with inputs', () => { const mockPackageWithConfigTemplates = ({ ...mockPackage, config_templates: [{ inputs: [{ type: 'foo' }] }], } as unknown) as PackageInfo; expect( - packageToPackageConfig(mockPackageWithConfigTemplates, '1', '2', 'default', 'pkgConfig-1') + packageToPackagePolicy(mockPackageWithConfigTemplates, '1', '2', 'default', 'pkgPolicy-1') ).toEqual({ - config_id: '1', + policy_id: '1', namespace: 'default', enabled: true, inputs: [{ type: 'foo', enabled: true, streams: [] }], - name: 'pkgConfig-1', + name: 'pkgPolicy-1', output_id: '2', package: { name: 'mock-package', diff --git a/x-pack/plugins/ingest_manager/common/services/package_to_config.ts b/x-pack/plugins/ingest_manager/common/services/package_to_package_policy.ts similarity index 65% rename from x-pack/plugins/ingest_manager/common/services/package_to_config.ts rename to x-pack/plugins/ingest_manager/common/services/package_to_package_policy.ts index 184b44cb9e5307..eab2e8ac2d745a 100644 --- a/x-pack/plugins/ingest_manager/common/services/package_to_config.ts +++ b/x-pack/plugins/ingest_manager/common/services/package_to_package_policy.ts @@ -8,12 +8,12 @@ import { RegistryConfigTemplate, RegistryVarsEntry, RegistryStream, - PackageConfig, - PackageConfigConfigRecord, - PackageConfigConfigRecordEntry, - PackageConfigInput, - PackageConfigInputStream, - NewPackageConfig, + PackagePolicy, + PackagePolicyConfigRecord, + PackagePolicyConfigRecordEntry, + PackagePolicyInput, + PackagePolicyInputStream, + NewPackagePolicy, } from '../types'; const getStreamsForInputType = ( @@ -40,27 +40,27 @@ const getStreamsForInputType = ( }; /* - * This service creates a package config inputs definition from defaults provided in package info + * This service creates a package policy inputs definition from defaults provided in package info */ -export const packageToPackageConfigInputs = (packageInfo: PackageInfo): PackageConfig['inputs'] => { - const inputs: PackageConfig['inputs'] = []; +export const packageToPackagePolicyInputs = (packageInfo: PackageInfo): PackagePolicy['inputs'] => { + const inputs: PackagePolicy['inputs'] = []; - // Assume package will only ever ship one package config template for now - const packageConfigTemplate: RegistryConfigTemplate | null = + // Assume package will only ever ship one package policy template for now + const packagePolicyTemplate: RegistryConfigTemplate | null = packageInfo.config_templates && packageInfo.config_templates[0] ? packageInfo.config_templates[0] : null; - // Create package config input property - if (packageConfigTemplate?.inputs?.length) { - // Map each package package config input to agent config package config input - packageConfigTemplate.inputs.forEach((packageInput) => { + // Create package policy input property + if (packagePolicyTemplate?.inputs?.length) { + // Map each package package policy input to agent policy package policy input + packagePolicyTemplate.inputs.forEach((packageInput) => { // Reduces registry var def into config object entry const varsReducer = ( - configObject: PackageConfigConfigRecord, + configObject: PackagePolicyConfigRecord, registryVar: RegistryVarsEntry - ): PackageConfigConfigRecord => { - const configEntry: PackageConfigConfigRecordEntry = { + ): PackagePolicyConfigRecord => { + const configEntry: PackagePolicyConfigRecordEntry = { value: !registryVar.default && registryVar.multi ? [] : registryVar.default, }; if (registryVar.type) { @@ -70,12 +70,12 @@ export const packageToPackageConfigInputs = (packageInfo: PackageInfo): PackageC return configObject; }; - // Map each package input stream into package config input stream - const streams: PackageConfigInputStream[] = getStreamsForInputType( + // Map each package input stream into package policy input stream + const streams: PackagePolicyInputStream[] = getStreamsForInputType( packageInput.type, packageInfo ).map((packageStream) => { - const stream: PackageConfigInputStream = { + const stream: PackagePolicyInputStream = { id: `${packageInput.type}-${packageStream.data_stream.dataset}`, enabled: packageStream.enabled === false ? false : true, data_stream: packageStream.data_stream, @@ -86,7 +86,7 @@ export const packageToPackageConfigInputs = (packageInfo: PackageInfo): PackageC return stream; }); - const input: PackageConfigInput = { + const input: PackagePolicyInput = { type: packageInput.type, enabled: streams.length ? !!streams.find((stream) => stream.enabled) : true, streams, @@ -104,23 +104,23 @@ export const packageToPackageConfigInputs = (packageInfo: PackageInfo): PackageC }; /** - * Builds a `NewPackageConfig` structure based on a package + * Builds a `NewPackagePolicy` structure based on a package * * @param packageInfo - * @param configId + * @param agentPolicyId * @param outputId - * @param packageConfigName + * @param packagePolicyName */ -export const packageToPackageConfig = ( +export const packageToPackagePolicy = ( packageInfo: PackageInfo, - configId: string, + agentPolicyId: string, outputId: string, namespace: string = '', - packageConfigName?: string, + packagePolicyName?: string, description?: string -): NewPackageConfig => { +): NewPackagePolicy => { return { - name: packageConfigName || `${packageInfo.name}-1`, + name: packagePolicyName || `${packageInfo.name}-1`, namespace, description, package: { @@ -129,8 +129,8 @@ export const packageToPackageConfig = ( version: packageInfo.version, }, enabled: true, - config_id: configId, + policy_id: agentPolicyId, output_id: outputId, - inputs: packageToPackageConfigInputs(packageInfo), + inputs: packageToPackagePolicyInputs(packageInfo), }; }; diff --git a/x-pack/plugins/ingest_manager/common/services/routes.ts b/x-pack/plugins/ingest_manager/common/services/routes.ts index 49de9a4d8fd854..1d802739a1b860 100644 --- a/x-pack/plugins/ingest_manager/common/services/routes.ts +++ b/x-pack/plugins/ingest_manager/common/services/routes.ts @@ -6,8 +6,8 @@ import { EPM_API_ROOT, EPM_API_ROUTES, - PACKAGE_CONFIG_API_ROUTES, - AGENT_CONFIG_API_ROUTES, + PACKAGE_POLICY_API_ROUTES, + AGENT_POLICY_API_ROUTES, DATA_STREAM_API_ROUTES, FLEET_SETUP_API_ROUTES, AGENT_API_ROUTES, @@ -48,61 +48,61 @@ export const epmRouteService = { }, }; -export const packageConfigRouteService = { +export const packagePolicyRouteService = { getListPath: () => { - return PACKAGE_CONFIG_API_ROUTES.LIST_PATTERN; + return PACKAGE_POLICY_API_ROUTES.LIST_PATTERN; }, - getInfoPath: (packageConfigId: string) => { - return PACKAGE_CONFIG_API_ROUTES.INFO_PATTERN.replace('{packageConfigId}', packageConfigId); + getInfoPath: (packagePolicyId: string) => { + return PACKAGE_POLICY_API_ROUTES.INFO_PATTERN.replace('{packagePolicyId}', packagePolicyId); }, getCreatePath: () => { - return PACKAGE_CONFIG_API_ROUTES.CREATE_PATTERN; + return PACKAGE_POLICY_API_ROUTES.CREATE_PATTERN; }, - getUpdatePath: (packageConfigId: string) => { - return PACKAGE_CONFIG_API_ROUTES.UPDATE_PATTERN.replace('{packageConfigId}', packageConfigId); + getUpdatePath: (packagePolicyId: string) => { + return PACKAGE_POLICY_API_ROUTES.UPDATE_PATTERN.replace('{packagePolicyId}', packagePolicyId); }, getDeletePath: () => { - return PACKAGE_CONFIG_API_ROUTES.DELETE_PATTERN; + return PACKAGE_POLICY_API_ROUTES.DELETE_PATTERN; }, }; -export const agentConfigRouteService = { +export const agentPolicyRouteService = { getListPath: () => { - return AGENT_CONFIG_API_ROUTES.LIST_PATTERN; + return AGENT_POLICY_API_ROUTES.LIST_PATTERN; }, - getInfoPath: (agentConfigId: string) => { - return AGENT_CONFIG_API_ROUTES.INFO_PATTERN.replace('{agentConfigId}', agentConfigId); + getInfoPath: (agentPolicyId: string) => { + return AGENT_POLICY_API_ROUTES.INFO_PATTERN.replace('{agentPolicyId}', agentPolicyId); }, getCreatePath: () => { - return AGENT_CONFIG_API_ROUTES.CREATE_PATTERN; + return AGENT_POLICY_API_ROUTES.CREATE_PATTERN; }, - getUpdatePath: (agentConfigId: string) => { - return AGENT_CONFIG_API_ROUTES.UPDATE_PATTERN.replace('{agentConfigId}', agentConfigId); + getUpdatePath: (agentPolicyId: string) => { + return AGENT_POLICY_API_ROUTES.UPDATE_PATTERN.replace('{agentPolicyId}', agentPolicyId); }, - getCopyPath: (agentConfigId: string) => { - return AGENT_CONFIG_API_ROUTES.COPY_PATTERN.replace('{agentConfigId}', agentConfigId); + getCopyPath: (agentPolicyId: string) => { + return AGENT_POLICY_API_ROUTES.COPY_PATTERN.replace('{agentPolicyId}', agentPolicyId); }, getDeletePath: () => { - return AGENT_CONFIG_API_ROUTES.DELETE_PATTERN; + return AGENT_POLICY_API_ROUTES.DELETE_PATTERN; }, - getInfoFullPath: (agentConfigId: string) => { - return AGENT_CONFIG_API_ROUTES.FULL_INFO_PATTERN.replace('{agentConfigId}', agentConfigId); + getInfoFullPath: (agentPolicyId: string) => { + return AGENT_POLICY_API_ROUTES.FULL_INFO_PATTERN.replace('{agentPolicyId}', agentPolicyId); }, - getInfoFullDownloadPath: (agentConfigId: string) => { - return AGENT_CONFIG_API_ROUTES.FULL_INFO_DOWNLOAD_PATTERN.replace( - '{agentConfigId}', - agentConfigId + getInfoFullDownloadPath: (agentPolicyId: string) => { + return AGENT_POLICY_API_ROUTES.FULL_INFO_DOWNLOAD_PATTERN.replace( + '{agentPolicyId}', + agentPolicyId ); }, }; diff --git a/x-pack/plugins/ingest_manager/common/types/index.ts b/x-pack/plugins/ingest_manager/common/types/index.ts index 69bcc498c18be4..cafd0f03f66e29 100644 --- a/x-pack/plugins/ingest_manager/common/types/index.ts +++ b/x-pack/plugins/ingest_manager/common/types/index.ts @@ -22,8 +22,8 @@ export interface IngestManagerConfigType { host?: string; ca_sha256?: string; }; - agentConfigRolloutRateLimitIntervalMs: number; - agentConfigRolloutRateLimitRequestPerInterval: number; + agentPolicyRolloutRateLimitIntervalMs: number; + agentPolicyRolloutRateLimitRequestPerInterval: number; }; } diff --git a/x-pack/plugins/ingest_manager/common/types/models/agent.ts b/x-pack/plugins/ingest_manager/common/types/models/agent.ts index f31d33e73c76f6..2b8a306577e7d2 100644 --- a/x-pack/plugins/ingest_manager/common/types/models/agent.ts +++ b/x-pack/plugins/ingest_manager/common/types/models/agent.ts @@ -64,7 +64,7 @@ export interface NewAgentEvent { payload?: any; agent_id: string; action_id?: string; - config_id?: string; + policy_id?: string; stream_id?: string; } @@ -89,8 +89,8 @@ interface AgentBase { access_api_key_id?: string; default_api_key?: string; default_api_key_id?: string; - config_id?: string; - config_revision?: number | null; + policy_id?: string; + policy_revision?: number | null; last_checkin?: string; last_checkin_status?: 'error' | 'online' | 'degraded'; user_provided_metadata: AgentMetadata; diff --git a/x-pack/plugins/ingest_manager/common/types/models/agent_config.ts b/x-pack/plugins/ingest_manager/common/types/models/agent_policy.ts similarity index 65% rename from x-pack/plugins/ingest_manager/common/types/models/agent_config.ts rename to x-pack/plugins/ingest_manager/common/types/models/agent_policy.ts index cdaea1cc5f9a4b..c626c85d3fb24f 100644 --- a/x-pack/plugins/ingest_manager/common/types/models/agent_config.ts +++ b/x-pack/plugins/ingest_manager/common/types/models/agent_policy.ts @@ -3,15 +3,15 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { PackageConfig, PackageConfigPackage } from './package_config'; +import { PackagePolicy, PackagePolicyPackage } from './package_policy'; import { Output } from './output'; -export enum AgentConfigStatus { +export enum AgentPolicyStatus { Active = 'active', Inactive = 'inactive', } -export interface NewAgentConfig { +export interface NewAgentPolicy { name: string; namespace: string; description?: string; @@ -19,18 +19,18 @@ export interface NewAgentConfig { monitoring_enabled?: Array<'logs' | 'metrics'>; } -export interface AgentConfig extends NewAgentConfig { +export interface AgentPolicy extends NewAgentPolicy { id: string; - status: AgentConfigStatus; - package_configs: string[] | PackageConfig[]; + status: AgentPolicyStatus; + package_policies: string[] | PackagePolicy[]; updated_at: string; updated_by: string; revision: number; } -export type AgentConfigSOAttributes = Omit; +export type AgentPolicySOAttributes = Omit; -export interface FullAgentConfigInputStream { +export interface FullAgentPolicyInputStream { id: string; data_stream: { dataset: string; @@ -39,28 +39,28 @@ export interface FullAgentConfigInputStream { [key: string]: any; } -export interface FullAgentConfigInput { +export interface FullAgentPolicyInput { id: string; name: string; type: string; data_stream: { namespace: string }; use_output: string; meta?: { - package?: Pick; + package?: Pick; [key: string]: unknown; }; - streams: FullAgentConfigInputStream[]; + streams: FullAgentPolicyInputStream[]; [key: string]: any; } -export interface FullAgentConfig { +export interface FullAgentPolicy { id: string; outputs: { [key: string]: Pick & { [key: string]: any; }; }; - inputs: FullAgentConfigInput[]; + inputs: FullAgentPolicyInput[]; revision?: number; agent?: { monitoring: { diff --git a/x-pack/plugins/ingest_manager/common/types/models/enrollment_api_key.ts b/x-pack/plugins/ingest_manager/common/types/models/enrollment_api_key.ts index 204ce4b15ea5b3..f39076ce1027b4 100644 --- a/x-pack/plugins/ingest_manager/common/types/models/enrollment_api_key.ts +++ b/x-pack/plugins/ingest_manager/common/types/models/enrollment_api_key.ts @@ -3,7 +3,6 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { SavedObjectAttributes } from 'src/core/public'; export interface EnrollmentAPIKey { id: string; @@ -11,13 +10,8 @@ export interface EnrollmentAPIKey { api_key: string; name?: string; active: boolean; - config_id?: string; + policy_id?: string; + created_at: string; } -export interface EnrollmentAPIKeySOAttributes extends SavedObjectAttributes { - api_key_id: string; - api_key: string; - name?: string; - active: boolean; - config_id?: string; -} +export type EnrollmentAPIKeySOAttributes = Omit; diff --git a/x-pack/plugins/ingest_manager/common/types/models/index.ts b/x-pack/plugins/ingest_manager/common/types/models/index.ts index 8ad716a4ba7685..ad4c6ad02639e2 100644 --- a/x-pack/plugins/ingest_manager/common/types/models/index.ts +++ b/x-pack/plugins/ingest_manager/common/types/models/index.ts @@ -5,8 +5,8 @@ */ export * from './agent'; -export * from './agent_config'; -export * from './package_config'; +export * from './agent_policy'; +export * from './package_policy'; export * from './data_stream'; export * from './output'; export * from './epm'; diff --git a/x-pack/plugins/ingest_manager/common/types/models/package_config.ts b/x-pack/plugins/ingest_manager/common/types/models/package_config.ts deleted file mode 100644 index 635afbd47850ed..00000000000000 --- a/x-pack/plugins/ingest_manager/common/types/models/package_config.ts +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -export interface PackageConfigPackage { - name: string; - title: string; - version: string; -} - -export interface PackageConfigConfigRecordEntry { - type?: string; - value?: any; -} - -export type PackageConfigConfigRecord = Record; - -export interface NewPackageConfigInputStream { - id: string; - enabled: boolean; - data_stream: { - dataset: string; - type: string; - }; - vars?: PackageConfigConfigRecord; - config?: PackageConfigConfigRecord; -} - -export interface PackageConfigInputStream extends NewPackageConfigInputStream { - compiled_stream?: any; -} - -export interface NewPackageConfigInput { - type: string; - enabled: boolean; - vars?: PackageConfigConfigRecord; - config?: PackageConfigConfigRecord; - streams: NewPackageConfigInputStream[]; -} - -export interface PackageConfigInput extends Omit { - streams: PackageConfigInputStream[]; -} - -export interface NewPackageConfig { - name: string; - description?: string; - namespace: string; - enabled: boolean; - config_id: string; - output_id: string; - package?: PackageConfigPackage; - inputs: NewPackageConfigInput[]; -} - -export interface UpdatePackageConfig extends NewPackageConfig { - version?: string; -} - -export interface PackageConfig extends Omit { - id: string; - inputs: PackageConfigInput[]; - version?: string; - revision: number; - updated_at: string; - updated_by: string; - created_at: string; - created_by: string; -} - -export type PackageConfigSOAttributes = Omit; diff --git a/x-pack/plugins/ingest_manager/common/types/models/package_policy.ts b/x-pack/plugins/ingest_manager/common/types/models/package_policy.ts new file mode 100644 index 00000000000000..724dbae5dac853 --- /dev/null +++ b/x-pack/plugins/ingest_manager/common/types/models/package_policy.ts @@ -0,0 +1,73 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export interface PackagePolicyPackage { + name: string; + title: string; + version: string; +} + +export interface PackagePolicyConfigRecordEntry { + type?: string; + value?: any; +} + +export type PackagePolicyConfigRecord = Record; + +export interface NewPackagePolicyInputStream { + id: string; + enabled: boolean; + data_stream: { + dataset: string; + type: string; + }; + vars?: PackagePolicyConfigRecord; + config?: PackagePolicyConfigRecord; +} + +export interface PackagePolicyInputStream extends NewPackagePolicyInputStream { + compiled_stream?: any; +} + +export interface NewPackagePolicyInput { + type: string; + enabled: boolean; + vars?: PackagePolicyConfigRecord; + config?: PackagePolicyConfigRecord; + streams: NewPackagePolicyInputStream[]; +} + +export interface PackagePolicyInput extends Omit { + streams: PackagePolicyInputStream[]; +} + +export interface NewPackagePolicy { + name: string; + description?: string; + namespace: string; + enabled: boolean; + policy_id: string; + output_id: string; + package?: PackagePolicyPackage; + inputs: NewPackagePolicyInput[]; +} + +export interface UpdatePackagePolicy extends NewPackagePolicy { + version?: string; +} + +export interface PackagePolicy extends Omit { + id: string; + inputs: PackagePolicyInput[]; + version?: string; + revision: number; + updated_at: string; + updated_by: string; + created_at: string; + created_by: string; +} + +export type PackagePolicySOAttributes = Omit; diff --git a/x-pack/plugins/ingest_manager/common/types/rest_spec/agent.ts b/x-pack/plugins/ingest_manager/common/types/rest_spec/agent.ts index 7ec5a8d68311f7..4a50938049a7b2 100644 --- a/x-pack/plugins/ingest_manager/common/types/rest_spec/agent.ts +++ b/x-pack/plugins/ingest_manager/common/types/rest_spec/agent.ts @@ -118,7 +118,7 @@ export interface PutAgentReassignRequest { params: { agentId: string; }; - body: { config_id: string }; + body: { policy_id: string }; } export interface PutAgentReassignResponse { @@ -161,7 +161,7 @@ export interface UpdateAgentRequest { export interface GetAgentStatusRequest { query: { - configId?: string; + policyId?: string; }; } diff --git a/x-pack/plugins/ingest_manager/common/types/rest_spec/agent_config.ts b/x-pack/plugins/ingest_manager/common/types/rest_spec/agent_config.ts deleted file mode 100644 index 4e1612d144edef..00000000000000 --- a/x-pack/plugins/ingest_manager/common/types/rest_spec/agent_config.ts +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -import { AgentConfig, NewAgentConfig, FullAgentConfig } from '../models'; -import { ListWithKuery } from './common'; - -export interface GetAgentConfigsRequest { - query: ListWithKuery & { - full?: boolean; - }; -} - -export type GetAgentConfigsResponseItem = AgentConfig & { agents?: number }; - -export interface GetAgentConfigsResponse { - items: GetAgentConfigsResponseItem[]; - total: number; - page: number; - perPage: number; - success: boolean; -} - -export interface GetOneAgentConfigRequest { - params: { - agentConfigId: string; - }; -} - -export interface GetOneAgentConfigResponse { - item: AgentConfig; - success: boolean; -} - -export interface CreateAgentConfigRequest { - body: NewAgentConfig; -} - -export interface CreateAgentConfigResponse { - item: AgentConfig; - success: boolean; -} - -export type UpdateAgentConfigRequest = GetOneAgentConfigRequest & { - body: NewAgentConfig; -}; - -export interface UpdateAgentConfigResponse { - item: AgentConfig; - success: boolean; -} - -export interface CopyAgentConfigRequest { - body: Pick; -} - -export interface CopyAgentConfigResponse { - item: AgentConfig; - success: boolean; -} - -export interface DeleteAgentConfigRequest { - body: { - agentConfigId: string; - }; -} - -export interface DeleteAgentConfigResponse { - id: string; - success: boolean; -} - -export interface GetFullAgentConfigRequest { - params: { - agentConfigId: string; - }; -} - -export interface GetFullAgentConfigResponse { - item: FullAgentConfig; - success: boolean; -} diff --git a/x-pack/plugins/ingest_manager/common/types/rest_spec/agent_policy.ts b/x-pack/plugins/ingest_manager/common/types/rest_spec/agent_policy.ts new file mode 100644 index 00000000000000..4683727ed51ac3 --- /dev/null +++ b/x-pack/plugins/ingest_manager/common/types/rest_spec/agent_policy.ts @@ -0,0 +1,83 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { AgentPolicy, NewAgentPolicy, FullAgentPolicy } from '../models'; +import { ListWithKuery } from './common'; + +export interface GetAgentPoliciesRequest { + query: ListWithKuery & { + full?: boolean; + }; +} + +export type GetAgentPoliciesResponseItem = AgentPolicy & { agents?: number }; + +export interface GetAgentPoliciesResponse { + items: GetAgentPoliciesResponseItem[]; + total: number; + page: number; + perPage: number; + success: boolean; +} + +export interface GetOneAgentPolicyRequest { + params: { + agentPolicyId: string; + }; +} + +export interface GetOneAgentPolicyResponse { + item: AgentPolicy; + success: boolean; +} + +export interface CreateAgentPolicyRequest { + body: NewAgentPolicy; +} + +export interface CreateAgentPolicyResponse { + item: AgentPolicy; + success: boolean; +} + +export type UpdateAgentPolicyRequest = GetOneAgentPolicyRequest & { + body: NewAgentPolicy; +}; + +export interface UpdateAgentPolicyResponse { + item: AgentPolicy; + success: boolean; +} + +export interface CopyAgentPolicyRequest { + body: Pick; +} + +export interface CopyAgentPolicyResponse { + item: AgentPolicy; + success: boolean; +} + +export interface DeleteAgentPolicyRequest { + body: { + agentPolicyId: string; + }; +} + +export interface DeleteAgentPolicyResponse { + id: string; + success: boolean; +} + +export interface GetFullAgentPolicyRequest { + params: { + agentPolicyId: string; + }; +} + +export interface GetFullAgentPolicyResponse { + item: FullAgentPolicy; + success: boolean; +} diff --git a/x-pack/plugins/ingest_manager/common/types/rest_spec/enrollment_api_key.ts b/x-pack/plugins/ingest_manager/common/types/rest_spec/enrollment_api_key.ts index 851e6571c0dd2a..1929955cac84c9 100644 --- a/x-pack/plugins/ingest_manager/common/types/rest_spec/enrollment_api_key.ts +++ b/x-pack/plugins/ingest_manager/common/types/rest_spec/enrollment_api_key.ts @@ -47,7 +47,7 @@ export interface DeleteEnrollmentAPIKeyResponse { export interface PostEnrollmentAPIKeyRequest { body: { name?: string; - config_id: string; + policy_id: string; expiration?: string; }; } diff --git a/x-pack/plugins/ingest_manager/common/types/rest_spec/index.ts b/x-pack/plugins/ingest_manager/common/types/rest_spec/index.ts index c40940fdbb6236..2916347693b980 100644 --- a/x-pack/plugins/ingest_manager/common/types/rest_spec/index.ts +++ b/x-pack/plugins/ingest_manager/common/types/rest_spec/index.ts @@ -4,10 +4,10 @@ * you may not use this file except in compliance with the Elastic License. */ export * from './common'; -export * from './package_config'; +export * from './package_policy'; export * from './data_stream'; export * from './agent'; -export * from './agent_config'; +export * from './agent_policy'; export * from './fleet_setup'; export * from './epm'; export * from './enrollment_api_key'; diff --git a/x-pack/plugins/ingest_manager/common/types/rest_spec/package_config.ts b/x-pack/plugins/ingest_manager/common/types/rest_spec/package_config.ts deleted file mode 100644 index e62645debb7487..00000000000000 --- a/x-pack/plugins/ingest_manager/common/types/rest_spec/package_config.ts +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -import { PackageConfig, NewPackageConfig, UpdatePackageConfig } from '../models'; - -export interface GetPackageConfigsRequest { - query: { - page: number; - perPage: number; - kuery?: string; - }; -} - -export interface GetPackageConfigsResponse { - items: PackageConfig[]; - total: number; - page: number; - perPage: number; - success: boolean; -} - -export interface GetOnePackageConfigRequest { - params: { - packageConfigId: string; - }; -} - -export interface GetOnePackageConfigResponse { - item: PackageConfig; - success: boolean; -} - -export interface CreatePackageConfigRequest { - body: NewPackageConfig; -} - -export interface CreatePackageConfigResponse { - item: PackageConfig; - success: boolean; -} - -export type UpdatePackageConfigRequest = GetOnePackageConfigRequest & { - body: UpdatePackageConfig; -}; - -export type UpdatePackageConfigResponse = CreatePackageConfigResponse; - -export interface DeletePackageConfigsRequest { - body: { - packageConfigIds: string[]; - }; -} - -export type DeletePackageConfigsResponse = Array<{ - id: string; - success: boolean; -}>; diff --git a/x-pack/plugins/ingest_manager/common/types/rest_spec/package_policy.ts b/x-pack/plugins/ingest_manager/common/types/rest_spec/package_policy.ts new file mode 100644 index 00000000000000..e5bba3d6deab3e --- /dev/null +++ b/x-pack/plugins/ingest_manager/common/types/rest_spec/package_policy.ts @@ -0,0 +1,59 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { PackagePolicy, NewPackagePolicy, UpdatePackagePolicy } from '../models'; + +export interface GetPackagePoliciesRequest { + query: { + page: number; + perPage: number; + kuery?: string; + }; +} + +export interface GetPackagePoliciesResponse { + items: PackagePolicy[]; + total: number; + page: number; + perPage: number; + success: boolean; +} + +export interface GetOnePackagePolicyRequest { + params: { + packagePolicyId: string; + }; +} + +export interface GetOnePackagePolicyResponse { + item: PackagePolicy; + success: boolean; +} + +export interface CreatePackagePolicyRequest { + body: NewPackagePolicy; +} + +export interface CreatePackagePolicyResponse { + item: PackagePolicy; + success: boolean; +} + +export type UpdatePackagePolicyRequest = GetOnePackagePolicyRequest & { + body: UpdatePackagePolicy; +}; + +export type UpdatePackagePolicyResponse = CreatePackagePolicyResponse; + +export interface DeletePackagePoliciesRequest { + body: { + packagePolicyIds: string[]; + }; +} + +export type DeletePackagePoliciesResponse = Array<{ + id: string; + success: boolean; +}>; diff --git a/x-pack/plugins/ingest_manager/dev_docs/actions_and_events.md b/x-pack/plugins/ingest_manager/dev_docs/actions_and_events.md index b41cdc221c51a3..f98a1c281e3eed 100644 --- a/x-pack/plugins/ingest_manager/dev_docs/actions_and_events.md +++ b/x-pack/plugins/ingest_manager/dev_docs/actions_and_events.md @@ -17,7 +17,7 @@ This action is send when a new policy is available, the policy is available unde "id": "action_id_1", "data": { "policy": { - "id": "config_id", + "id": "policy_id", "outputs": { "default": { "api_key": "slfhsdlfhjjkshfkjh:sdfsdfsdfsdf", diff --git a/x-pack/plugins/ingest_manager/dev_docs/api/agents_enroll.md b/x-pack/plugins/ingest_manager/dev_docs/api/agents_enroll.md index 304ce733b7dcd2..b32e6873c60e57 100644 --- a/x-pack/plugins/ingest_manager/dev_docs/api/agents_enroll.md +++ b/x-pack/plugins/ingest_manager/dev_docs/api/agents_enroll.md @@ -45,7 +45,7 @@ The API returns the following: "item": { "id": "a4937110-e53e-11e9-934f-47a8e38a522c", "active": true, - "config_id": "default", + "policy_id": "default", "type": "PERMANENT", "enrolled_at": "2019-10-02T18:01:22.337Z", "user_provided_metadata": {}, diff --git a/x-pack/plugins/ingest_manager/dev_docs/definitions.md b/x-pack/plugins/ingest_manager/dev_docs/definitions.md index bd207806110554..be5aeb923e903b 100644 --- a/x-pack/plugins/ingest_manager/dev_docs/definitions.md +++ b/x-pack/plugins/ingest_manager/dev_docs/definitions.md @@ -5,12 +5,12 @@ Overall documentation of Ingest Management is now maintained in the `elastic/sta This section is to define terms used across ingest management. -## Package Config +## Package policy -A package config is a definition on how to collect data from a service, for example `nginx`. A package config contains +A package policy is a definition on how to collect data from a service, for example `nginx`. A package policy contains definitions for one or multiple inputs and each input can contain one or multiple streams. -With the example of the nginx Package Config, it contains two inputs: `logs` and `nginx/metrics`. Logs and metrics are collected +With the example of the nginx Package policy, it contains two inputs: `logs` and `nginx/metrics`. Logs and metrics are collected differently. The `logs` input contains two streams, `access` and `error`, the `nginx/metrics` input contains the stubstatus stream. ## Data Stream @@ -20,7 +20,7 @@ ingesting data and the setup of Elasticsearch. ## Elastic Agent -A single, unified agent that users can deploy to hosts or containers. It controls which data is collected from the host or containers and where the data is sent. It will run Beats, Endpoint or other monitoring programs as needed. It can operate standalone or pull a configuration policy from Fleet. +A single, unified agent that users can deploy to hosts or containers. It controls which data is collected from the host or containers and where the data is sent. It will run Beats, Endpoint or other monitoring programs as needed. It can operate standalone or pull an agent policy from Fleet. ## Elastic Package Registry @@ -29,8 +29,7 @@ More details about the registry can be found [here](https://github.com/elastic/p ## Fleet -Fleet is the part of the Ingest Manager UI in Kibana that handles the part of enrolling Elastic Agents, -managing agents and sending configurations to the Elastic Agent. +Fleet is the part of the Ingest Manager UI in Kibana that handles the part of enrolling Elastic Agents, managing agents and sending policies to the Elastic Agent. ## Indexing Strategy @@ -40,15 +39,15 @@ the index strategy is sent to Data Streams. ## Input -An input is the configuration unit in an Agent Config that defines the options on how to collect data from +An input is the configuration unit in an Agent policy that defines the options on how to collect data from an endpoint. This could be username / password which are need to authenticate with a service or a host url as an example. -An input is part of a Package Config and contains streams. +An input is part of a Package policy and contains streams. ## Integration -An integration is a package with the type integration. An integration package has at least 1 package config +An integration is a package with the type integration. An integration package has at least 1 package policy and usually collects data from / about a service. ## Namespace @@ -60,9 +59,9 @@ A user-specified string that will be used to part of the index name in Elasticse A package contains all the assets for the Elastic Stack. A more detailed definition of a package can be found under https://github.com/elastic/package-registry. -Besides the assets, a package contains the package config definitions with its inputs and streams. +Besides the assets, a package contains the package policy definitions with its inputs and streams. ## Stream -A stream is a configuration unit in the Elastic Agent config. A stream is part of an input and defines how the data +A stream is a configuration unit in the Elastic Agent policy. A stream is part of an input and defines how the data fetched by this input should be processed and which Data Stream to send it to. diff --git a/x-pack/plugins/ingest_manager/dev_docs/epm.md b/x-pack/plugins/ingest_manager/dev_docs/epm.md index abcab718f7ab9a..20209d09e6cc21 100644 --- a/x-pack/plugins/ingest_manager/dev_docs/epm.md +++ b/x-pack/plugins/ingest_manager/dev_docs/epm.md @@ -5,26 +5,26 @@ Overall documentation of Ingest Management is now maintained in the `elastic/sta When upgrading a package between a bugfix or a minor version, no breaking changes should happen. Upgrading a package has the following effect: -* Removal of existing dashboards -* Installation of new dashboards -* Write new ingest pipelines with the version -* Write new Elasticsearch alias templates -* Trigger a rollover for all the affected indices +- Removal of existing dashboards +- Installation of new dashboards +- Write new ingest pipelines with the version +- Write new Elasticsearch alias templates +- Trigger a rollover for all the affected indices -The new ingest pipeline is expected to still work with the data coming from older configurations. In most cases this means some of the fields can be missing. For this to work, each event must contain the version of config / package it is coming from to make such a decision. +The new ingest pipeline is expected to still work with the data coming from older policies. In most cases this means some of the fields can be missing. For this to work, each event must contain the version of policy / package it is coming from to make such a decision. In case of a breaking change in the data structure, the new ingest pipeline is also expected to deal with this change. In case there are breaking changes which cannot be dealt with in an ingest pipeline, a new package has to be created. -Each package lists its minimal required agent version. In case there are agents enrolled with an older version, the user is notified to upgrade these agents as otherwise the new configs cannot be rolled out. +Each package lists its minimal required agent version. In case there are agents enrolled with an older version, the user is notified to upgrade these agents as otherwise the new policies cannot be rolled out. # Generated assets -When a package is installed or upgraded, certain Kibana and Elasticsearch assets are generated from . These follow the naming conventions explained above (see "indexing strategy") and contain configuration for the elastic stack that makes ingesting and displaying data work with as little user interaction as possible. +When a package is installed or upgraded, certain Kibana and Elasticsearch assets are generated from . These follow the naming conventions explained above (see "indexing strategy") and contain configuration for the Elastic stack that makes ingesting and displaying data work with as little user interaction as possible. ## Elasticsearch Index Templates ### Generation -* Index templates are generated from `YAML` files contained in the package. -* There is one index template per dataset. -* For the generation of an index template, all `yml` files contained in the package subdirectory `dataset/DATASET_NAME/fields/` are used. \ No newline at end of file +- Index templates are generated from `YAML` files contained in the package. +- There is one index template per dataset. +- For the generation of an index template, all `yml` files contained in the package subdirectory `dataset/DATASET_NAME/fields/` are used. diff --git a/x-pack/plugins/ingest_manager/dev_docs/fleet_agents_interactions_detailed.md b/x-pack/plugins/ingest_manager/dev_docs/fleet_agents_interactions_detailed.md index d563712fdf0a69..52a1dde37cd079 100644 --- a/x-pack/plugins/ingest_manager/dev_docs/fleet_agents_interactions_detailed.md +++ b/x-pack/plugins/ingest_manager/dev_docs/fleet_agents_interactions_detailed.md @@ -5,7 +5,7 @@ Fleet workflow: - an agent enroll to fleet using an enrollment token. -- Every n seconds agent is polling the checkin API to send events and check for new configuration +- Every n seconds agent is polling the checkin API to send events and check for new policy ### Agent enrollment @@ -13,7 +13,7 @@ An agent must enroll using the REST Api provided by fleet. When an agent enroll Fleet: - verify the Enrollment token is a valid ES API key -- retrieve the Saved Object (SO) associated to this api key id (this SO contains the configuration|policy id) +- retrieve the Saved Object (SO) associated to this api key id (this SO contains the agent policy id) - create an ES ApiKey unique to the agent for accessing kibana during checkin - create an ES ApiKey per output to send logs and metrics to the output - Save the new agent in a SO with keys encrypted inside the agent SO object @@ -22,15 +22,15 @@ When an agent enroll Fleet: ### Agent checkin -Agent are going to poll the checkin API to send events and check for new configration. To checkin agent are going to use the REST Api provided by fleet. +Agent are going to poll the checkin API to send events and check for new policy. To checkin agent are going to use the REST Api provided by fleet. When an agent checkin fleet: - verify the access token is a valid ES API key - retrieve the agent (SO associated to this api key id) - Insert events SO -- If the Agent configuration has been updated since last checkin - - generate the agent config +- If the Agent policy has been updated since last checkin + - generate the agent policy - Create the missing API key for agent -> ES communication - Save the new agent (with last checkin date) in a SavedObject with keys encrypted inside the agent @@ -44,6 +44,6 @@ An agent can acknowledge one or multiple actions by calling `POST /api/ingest_ma ## Other interactions -### Agent Configuration update +### Agent policy update -When a configuration is updated, every SO agent running this configuration is updated with a timestamp of the latest config. +When a policy is updated, every SO agent running this policy is updated with a timestamp of the latest policy. diff --git a/x-pack/plugins/ingest_manager/dev_docs/schema/agent_checkin.mml b/x-pack/plugins/ingest_manager/dev_docs/schema/agent_checkin.mml index a5332c50ab9472..377c6a30fa230e 100644 --- a/x-pack/plugins/ingest_manager/dev_docs/schema/agent_checkin.mml +++ b/x-pack/plugins/ingest_manager/dev_docs/schema/agent_checkin.mml @@ -12,8 +12,8 @@ sequenceDiagram Note right of SavedObjects: encrypted SO here end - alt If configuration updated since last checkin - Fleet API->>SavedObjects: getAgentConfiguration(configId) + alt If policy updated since last checkin + Fleet API->>SavedObjects: getAgentPolicy(agentPolicyId) opt If there is not API Key for default output Fleet API->>Elasticsearch: createAgentESApiKey() @@ -34,4 +34,4 @@ sequenceDiagram end - Fleet API->>Agent: actions|agent config + Fleet API->>Agent: actions|agent policy diff --git a/x-pack/plugins/ingest_manager/dev_docs/schema/saved_objects.mml b/x-pack/plugins/ingest_manager/dev_docs/schema/saved_objects.mml index d157bf32fa66b7..9f73a15bed2eb1 100644 --- a/x-pack/plugins/ingest_manager/dev_docs/schema/saved_objects.mml +++ b/x-pack/plugins/ingest_manager/dev_docs/schema/saved_objects.mml @@ -1,11 +1,11 @@ classDiagram - agent_configs "1" -- "*" package_configs - agent_configs "1" -- "*" enrollment_api_keys - agent_configs "1" -- "*" agents : is used - agent_configs "*" -- "*" outputs + agent_policies "1" -- "*" package_policies + agent_policies "1" -- "*" enrollment_api_keys + agent_policies "1" -- "*" agents : is used + agent_policies "*" -- "*" outputs agents "1" -- "*" agent_events agents "1" -- "*" agent_events - package "1" -- "*" package_configs + package "1" -- "*" package_policies class package { installed @@ -14,11 +14,11 @@ classDiagram class agents { status access_api_key_id - config_id + policy_id last_checkin local_metadata user_provided_metadata - actions // Encrypted contains new agent config + actions // Encrypted contains new agent policy default_api_key // Encrypted } @@ -28,7 +28,7 @@ classDiagram subtype agent_id action_id - config_id + policy_id stream_id timestamp message @@ -36,18 +36,18 @@ classDiagram data } - class agent_configs { - package_configs // package_config ids + class agent_policies { + package_policies // package_policy ids name namespace description status } - class package_configs { + class package_policies { name namespace - config_id + policy_id enabled package output_id @@ -64,7 +64,7 @@ classDiagram } class enrollment_api_keys { - config_id + policy_id api_key_id api_key // Encrypted } diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/home_integration/tutorial_directory_notice.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/home_integration/tutorial_directory_notice.tsx index 553623380dcc05..bc5435369f44a0 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/home_integration/tutorial_directory_notice.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/home_integration/tutorial_directory_notice.tsx @@ -82,7 +82,7 @@ export const TutorialDirectoryNotice: TutorialDirectoryNoticeComponent = memo(() diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/settings_flyout.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/settings_flyout.tsx index e8081e097fd429..be1b3df8a0c3eb 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/settings_flyout.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/settings_flyout.tsx @@ -167,7 +167,7 @@ export const SettingFlyout: React.FunctionComponent = ({ onClose }) => { 'xpack.ingestManager.settings.integrationUpgradeEnabledFieldLabel', { defaultMessage: - 'Automatically update integrations to the latest version to receive the latest assets. Agent configurations may need to be updated in order to use new features.', + 'Automatically update integrations to the latest version to receive the latest assets. Agent policies may need to be updated in order to use new features.', } ), }, @@ -210,7 +210,7 @@ export const SettingFlyout: React.FunctionComponent = ({ onClose }) => { diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/constants/index.ts b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/constants/index.ts index d31d66d889c965..185e1fa5eb0ce1 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/constants/index.ts +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/constants/index.ts @@ -7,11 +7,11 @@ export { PLUGIN_ID, EPM_API_ROUTES, AGENT_API_ROUTES, - AGENT_CONFIG_SAVED_OBJECT_TYPE, + AGENT_POLICY_SAVED_OBJECT_TYPE, AGENT_EVENT_SAVED_OBJECT_TYPE, AGENT_SAVED_OBJECT_TYPE, ENROLLMENT_API_KEYS_SAVED_OBJECT_TYPE, - PACKAGE_CONFIG_SAVED_OBJECT_TYPE, + PACKAGE_POLICY_SAVED_OBJECT_TYPE, } from '../../../../common'; export * from './page_paths'; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/constants/page_paths.ts b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/constants/page_paths.ts index 9f1088a94aa946..4a8dcfedc09361 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/constants/page_paths.ts +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/constants/page_paths.ts @@ -9,17 +9,17 @@ export type StaticPage = | 'integrations' | 'integrations_all' | 'integrations_installed' - | 'configurations' - | 'configurations_list' + | 'policies' + | 'policies_list' | 'fleet' | 'fleet_enrollment_tokens' | 'data_streams'; export type DynamicPage = | 'integration_details' - | 'configuration_details' - | 'add_integration_from_configuration' - | 'add_integration_to_configuration' + | 'policy_details' + | 'add_integration_from_policy' + | 'add_integration_to_policy' | 'edit_integration' | 'fleet_agent_list' | 'fleet_agent_details'; @@ -40,13 +40,13 @@ export const PAGE_ROUTING_PATHS = { integrations_all: '/integrations', integrations_installed: '/integrations/installed', integration_details: '/integrations/detail/:pkgkey/:panel?', - configurations: '/configs', - configurations_list: '/configs', - configuration_details: '/configs/:configId/:tabId?', - configuration_details_settings: '/configs/:configId/settings', - add_integration_from_configuration: '/configs/:configId/add-integration', - add_integration_to_configuration: '/integrations/:pkgkey/add-integration', - edit_integration: '/configs/:configId/edit-integration/:packageConfigId', + policies: '/policies', + policies_list: '/policies', + policy_details: '/policies/:policyId/:tabId?', + policy_details_settings: '/policies/:policyId/settings', + add_integration_from_policy: '/policies/:policyId/add-integration', + add_integration_to_policy: '/integrations/:pkgkey/add-integration', + edit_integration: '/policies/:policyId/edit-integration/:packagePolicyId', fleet: '/fleet', fleet_agent_list: '/fleet/agents', fleet_agent_details: '/fleet/agents/:agentId/:tabId?', @@ -68,13 +68,13 @@ export const pagePathGetters: { integrations_installed: () => '/integrations/installed', integration_details: ({ pkgkey, panel }) => `/integrations/detail/${pkgkey}${panel ? `/${panel}` : ''}`, - configurations: () => '/configs', - configurations_list: () => '/configs', - configuration_details: ({ configId, tabId }) => `/configs/${configId}${tabId ? `/${tabId}` : ''}`, - add_integration_from_configuration: ({ configId }) => `/configs/${configId}/add-integration`, - add_integration_to_configuration: ({ pkgkey }) => `/integrations/${pkgkey}/add-integration`, - edit_integration: ({ configId, packageConfigId }) => - `/configs/${configId}/edit-integration/${packageConfigId}`, + policies: () => '/policies', + policies_list: () => '/policies', + policy_details: ({ policyId, tabId }) => `/policies/${policyId}${tabId ? `/${tabId}` : ''}`, + add_integration_from_policy: ({ policyId }) => `/policies/${policyId}/add-integration`, + add_integration_to_policy: ({ pkgkey }) => `/integrations/${pkgkey}/add-integration`, + edit_integration: ({ policyId, packagePolicyId }) => + `/policies/${policyId}/edit-integration/${packagePolicyId}`, fleet: () => '/fleet', fleet_agent_list: ({ kuery }) => `/fleet/agents${kuery ? `?kuery=${kuery}` : ''}`, fleet_agent_details: ({ agentId, tabId }) => diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_breadcrumbs.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_breadcrumbs.tsx index 293638cff50bf1..6ef1351dc5b603 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_breadcrumbs.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_breadcrumbs.tsx @@ -72,51 +72,51 @@ const breadcrumbGetters: { }, { text: pkgTitle }, ], - configurations: () => [ + policies: () => [ BASE_BREADCRUMB, { - text: i18n.translate('xpack.ingestManager.breadcrumbs.configurationsPageTitle', { - defaultMessage: 'Configurations', + text: i18n.translate('xpack.ingestManager.breadcrumbs.policiesPageTitle', { + defaultMessage: 'Policies', }), }, ], - configurations_list: () => [ + policies_list: () => [ BASE_BREADCRUMB, { - text: i18n.translate('xpack.ingestManager.breadcrumbs.configurationsPageTitle', { - defaultMessage: 'Configurations', + text: i18n.translate('xpack.ingestManager.breadcrumbs.policiesPageTitle', { + defaultMessage: 'Policies', }), }, ], - configuration_details: ({ configName }) => [ + policy_details: ({ policyName }) => [ BASE_BREADCRUMB, { - href: pagePathGetters.configurations(), - text: i18n.translate('xpack.ingestManager.breadcrumbs.configurationsPageTitle', { - defaultMessage: 'Configurations', + href: pagePathGetters.policies(), + text: i18n.translate('xpack.ingestManager.breadcrumbs.policiesPageTitle', { + defaultMessage: 'Policies', }), }, - { text: configName }, + { text: policyName }, ], - add_integration_from_configuration: ({ configName, configId }) => [ + add_integration_from_policy: ({ policyName, policyId }) => [ BASE_BREADCRUMB, { - href: pagePathGetters.configurations(), - text: i18n.translate('xpack.ingestManager.breadcrumbs.configurationsPageTitle', { - defaultMessage: 'Configurations', + href: pagePathGetters.policies(), + text: i18n.translate('xpack.ingestManager.breadcrumbs.policiesPageTitle', { + defaultMessage: 'Policies', }), }, { - href: pagePathGetters.configuration_details({ configId }), - text: configName, + href: pagePathGetters.policy_details({ policyId }), + text: policyName, }, { - text: i18n.translate('xpack.ingestManager.breadcrumbs.addPackageConfigPageTitle', { + text: i18n.translate('xpack.ingestManager.breadcrumbs.addPackagePolicyPageTitle', { defaultMessage: 'Add integration', }), }, ], - add_integration_to_configuration: ({ pkgTitle, pkgkey }) => [ + add_integration_to_policy: ({ pkgTitle, pkgkey }) => [ BASE_BREADCRUMB, { href: pagePathGetters.integrations(), @@ -129,25 +129,25 @@ const breadcrumbGetters: { text: pkgTitle, }, { - text: i18n.translate('xpack.ingestManager.breadcrumbs.addPackageConfigPageTitle', { + text: i18n.translate('xpack.ingestManager.breadcrumbs.addPackagePolicyPageTitle', { defaultMessage: 'Add integration', }), }, ], - edit_integration: ({ configName, configId }) => [ + edit_integration: ({ policyName, policyId }) => [ BASE_BREADCRUMB, { - href: pagePathGetters.configurations(), - text: i18n.translate('xpack.ingestManager.breadcrumbs.configurationsPageTitle', { - defaultMessage: 'Configurations', + href: pagePathGetters.policies(), + text: i18n.translate('xpack.ingestManager.breadcrumbs.policiesPageTitle', { + defaultMessage: 'Policies', }), }, { - href: pagePathGetters.configuration_details({ configId }), - text: configName, + href: pagePathGetters.policy_details({ policyId }), + text: policyName, }, { - text: i18n.translate('xpack.ingestManager.breadcrumbs.editPackageConfigPageTitle', { + text: i18n.translate('xpack.ingestManager.breadcrumbs.editPackagePolicyPageTitle', { defaultMessage: 'Edit integration', }), }, diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_request/agent_config.ts b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_request/agent_config.ts deleted file mode 100644 index 0bb09c27310327..00000000000000 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_request/agent_config.ts +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -import { - useRequest, - sendRequest, - useConditionalRequest, - SendConditionalRequestConfig, -} from './use_request'; -import { agentConfigRouteService } from '../../services'; -import { - GetAgentConfigsRequest, - GetAgentConfigsResponse, - GetOneAgentConfigResponse, - GetFullAgentConfigResponse, - CreateAgentConfigRequest, - CreateAgentConfigResponse, - UpdateAgentConfigRequest, - UpdateAgentConfigResponse, - CopyAgentConfigRequest, - CopyAgentConfigResponse, - DeleteAgentConfigRequest, - DeleteAgentConfigResponse, -} from '../../types'; - -export const useGetAgentConfigs = (query?: GetAgentConfigsRequest['query']) => { - return useRequest({ - path: agentConfigRouteService.getListPath(), - method: 'get', - query, - }); -}; - -export const useGetOneAgentConfig = (agentConfigId: string | undefined) => { - return useConditionalRequest({ - path: agentConfigId ? agentConfigRouteService.getInfoPath(agentConfigId) : undefined, - method: 'get', - shouldSendRequest: !!agentConfigId, - } as SendConditionalRequestConfig); -}; - -export const useGetOneAgentConfigFull = (agentConfigId: string) => { - return useRequest({ - path: agentConfigRouteService.getInfoFullPath(agentConfigId), - method: 'get', - }); -}; - -export const sendGetOneAgentConfigFull = ( - agentConfigId: string, - query: { standalone?: boolean } = {} -) => { - return sendRequest({ - path: agentConfigRouteService.getInfoFullPath(agentConfigId), - method: 'get', - query, - }); -}; - -export const sendGetOneAgentConfig = (agentConfigId: string) => { - return sendRequest({ - path: agentConfigRouteService.getInfoPath(agentConfigId), - method: 'get', - }); -}; - -export const sendCreateAgentConfig = ( - body: CreateAgentConfigRequest['body'], - { withSysMonitoring }: { withSysMonitoring: boolean } = { withSysMonitoring: false } -) => { - return sendRequest({ - path: agentConfigRouteService.getCreatePath(), - method: 'post', - body: JSON.stringify(body), - query: withSysMonitoring ? { sys_monitoring: true } : {}, - }); -}; - -export const sendUpdateAgentConfig = ( - agentConfigId: string, - body: UpdateAgentConfigRequest['body'] -) => { - return sendRequest({ - path: agentConfigRouteService.getUpdatePath(agentConfigId), - method: 'put', - body: JSON.stringify(body), - }); -}; - -export const sendCopyAgentConfig = ( - agentConfigId: string, - body: CopyAgentConfigRequest['body'] -) => { - return sendRequest({ - path: agentConfigRouteService.getCopyPath(agentConfigId), - method: 'post', - body: JSON.stringify(body), - }); -}; - -export const sendDeleteAgentConfig = (body: DeleteAgentConfigRequest['body']) => { - return sendRequest({ - path: agentConfigRouteService.getDeletePath(), - method: 'post', - body: JSON.stringify(body), - }); -}; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_request/agent_policy.ts b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_request/agent_policy.ts new file mode 100644 index 00000000000000..8707dcab9e5841 --- /dev/null +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_request/agent_policy.ts @@ -0,0 +1,109 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { + useRequest, + sendRequest, + useConditionalRequest, + SendConditionalRequestConfig, +} from './use_request'; +import { agentPolicyRouteService } from '../../services'; +import { + GetAgentPoliciesRequest, + GetAgentPoliciesResponse, + GetOneAgentPolicyResponse, + GetFullAgentPolicyResponse, + CreateAgentPolicyRequest, + CreateAgentPolicyResponse, + UpdateAgentPolicyRequest, + UpdateAgentPolicyResponse, + CopyAgentPolicyRequest, + CopyAgentPolicyResponse, + DeleteAgentPolicyRequest, + DeleteAgentPolicyResponse, +} from '../../types'; + +export const useGetAgentPolicies = (query?: GetAgentPoliciesRequest['query']) => { + return useRequest({ + path: agentPolicyRouteService.getListPath(), + method: 'get', + query, + }); +}; + +export const useGetOneAgentPolicy = (agentPolicyId: string | undefined) => { + return useConditionalRequest({ + path: agentPolicyId ? agentPolicyRouteService.getInfoPath(agentPolicyId) : undefined, + method: 'get', + shouldSendRequest: !!agentPolicyId, + } as SendConditionalRequestConfig); +}; + +export const useGetOneAgentPolicyFull = (agentPolicyId: string) => { + return useRequest({ + path: agentPolicyRouteService.getInfoFullPath(agentPolicyId), + method: 'get', + }); +}; + +export const sendGetOneAgentPolicyFull = ( + agentPolicyId: string, + query: { standalone?: boolean } = {} +) => { + return sendRequest({ + path: agentPolicyRouteService.getInfoFullPath(agentPolicyId), + method: 'get', + query, + }); +}; + +export const sendGetOneAgentPolicy = (agentPolicyId: string) => { + return sendRequest({ + path: agentPolicyRouteService.getInfoPath(agentPolicyId), + method: 'get', + }); +}; + +export const sendCreateAgentPolicy = ( + body: CreateAgentPolicyRequest['body'], + { withSysMonitoring }: { withSysMonitoring: boolean } = { withSysMonitoring: false } +) => { + return sendRequest({ + path: agentPolicyRouteService.getCreatePath(), + method: 'post', + body: JSON.stringify(body), + query: withSysMonitoring ? { sys_monitoring: true } : {}, + }); +}; + +export const sendUpdateAgentPolicy = ( + agentPolicyId: string, + body: UpdateAgentPolicyRequest['body'] +) => { + return sendRequest({ + path: agentPolicyRouteService.getUpdatePath(agentPolicyId), + method: 'put', + body: JSON.stringify(body), + }); +}; + +export const sendCopyAgentPolicy = ( + agentPolicyId: string, + body: CopyAgentPolicyRequest['body'] +) => { + return sendRequest({ + path: agentPolicyRouteService.getCopyPath(agentPolicyId), + method: 'post', + body: JSON.stringify(body), + }); +}; + +export const sendDeleteAgentPolicy = (body: DeleteAgentPolicyRequest['body']) => { + return sendRequest({ + path: agentPolicyRouteService.getDeletePath(), + method: 'post', + body: JSON.stringify(body), + }); +}; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_request/index.ts b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_request/index.ts index 0d703925f2cf3d..e33684b5a0926b 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_request/index.ts +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_request/index.ts @@ -4,8 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ export { setHttpClient, sendRequest, useRequest } from './use_request'; -export * from './agent_config'; -export * from './package_config'; +export * from './agent_policy'; +export * from './package_policy'; export * from './data_stream'; export * from './agents'; export * from './enrollment_api_keys'; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_request/package_config.ts b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_request/package_config.ts deleted file mode 100644 index aba950123ead31..00000000000000 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_request/package_config.ts +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -import { sendRequest, useRequest } from './use_request'; -import { packageConfigRouteService } from '../../services'; -import { - CreatePackageConfigRequest, - CreatePackageConfigResponse, - UpdatePackageConfigRequest, - UpdatePackageConfigResponse, -} from '../../types'; -import { - DeletePackageConfigsRequest, - DeletePackageConfigsResponse, - GetPackageConfigsRequest, - GetPackageConfigsResponse, - GetOnePackageConfigResponse, -} from '../../../../../common/types/rest_spec'; - -export const sendCreatePackageConfig = (body: CreatePackageConfigRequest['body']) => { - return sendRequest({ - path: packageConfigRouteService.getCreatePath(), - method: 'post', - body: JSON.stringify(body), - }); -}; - -export const sendUpdatePackageConfig = ( - packageConfigId: string, - body: UpdatePackageConfigRequest['body'] -) => { - return sendRequest({ - path: packageConfigRouteService.getUpdatePath(packageConfigId), - method: 'put', - body: JSON.stringify(body), - }); -}; - -export const sendDeletePackageConfig = (body: DeletePackageConfigsRequest['body']) => { - return sendRequest({ - path: packageConfigRouteService.getDeletePath(), - method: 'post', - body: JSON.stringify(body), - }); -}; - -export function useGetPackageConfigs(query: GetPackageConfigsRequest['query']) { - return useRequest({ - method: 'get', - path: packageConfigRouteService.getListPath(), - query, - }); -} - -export const sendGetOnePackageConfig = (packageConfigId: string) => { - return sendRequest({ - path: packageConfigRouteService.getInfoPath(packageConfigId), - method: 'get', - }); -}; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_request/package_policy.ts b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_request/package_policy.ts new file mode 100644 index 00000000000000..47a38ba3bfeae8 --- /dev/null +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/hooks/use_request/package_policy.ts @@ -0,0 +1,62 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { sendRequest, useRequest } from './use_request'; +import { packagePolicyRouteService } from '../../services'; +import { + CreatePackagePolicyRequest, + CreatePackagePolicyResponse, + UpdatePackagePolicyRequest, + UpdatePackagePolicyResponse, +} from '../../types'; +import { + DeletePackagePoliciesRequest, + DeletePackagePoliciesResponse, + GetPackagePoliciesRequest, + GetPackagePoliciesResponse, + GetOnePackagePolicyResponse, +} from '../../../../../common/types/rest_spec'; + +export const sendCreatePackagePolicy = (body: CreatePackagePolicyRequest['body']) => { + return sendRequest({ + path: packagePolicyRouteService.getCreatePath(), + method: 'post', + body: JSON.stringify(body), + }); +}; + +export const sendUpdatePackagePolicy = ( + packagePolicyId: string, + body: UpdatePackagePolicyRequest['body'] +) => { + return sendRequest({ + path: packagePolicyRouteService.getUpdatePath(packagePolicyId), + method: 'put', + body: JSON.stringify(body), + }); +}; + +export const sendDeletePackagePolicy = (body: DeletePackagePoliciesRequest['body']) => { + return sendRequest({ + path: packagePolicyRouteService.getDeletePath(), + method: 'post', + body: JSON.stringify(body), + }); +}; + +export function useGetPackagePolicies(query: GetPackagePoliciesRequest['query']) { + return useRequest({ + method: 'get', + path: packagePolicyRouteService.getListPath(), + query, + }); +} + +export const sendGetOnePackagePolicy = (packagePolicyId: string) => { + return sendRequest({ + path: packagePolicyRouteService.getInfoPath(packagePolicyId), + method: 'get', + }); +}; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/index.tsx index 443708ec6384fd..5520a50463db44 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/index.tsx @@ -21,7 +21,7 @@ import { import { PAGE_ROUTING_PATHS } from './constants'; import { DefaultLayout, WithoutHeaderLayout } from './layouts'; import { Loading, Error } from './components'; -import { IngestManagerOverview, EPMApp, AgentConfigApp, FleetApp, DataStreamApp } from './sections'; +import { IngestManagerOverview, EPMApp, AgentPolicyApp, FleetApp, DataStreamApp } from './sections'; import { DepsContext, ConfigContext, useConfig } from './hooks'; import { PackageInstallProvider } from './sections/epm/hooks'; import { useCore, sendSetup, sendGetPermissionsCheck } from './hooks'; @@ -190,9 +190,9 @@ const IngestManagerRoutes = memo<{ history: AppMountParameters['history']; basep - - - + + + diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/layouts/default.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/layouts/default.tsx index 09da96fac4462f..3a68cb948eb2d5 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/layouts/default.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/layouts/default.tsx @@ -77,13 +77,10 @@ export const DefaultLayout: React.FunctionComponent = ({ defaultMessage="Integrations" /> - + ; - -type AllowedPackageKey = 'endpoint'; -const PackageConfigMapping: { - [key: string]: CustomConfigurePackageConfigContent; -} = {}; - -/** - * Plugins can call this function from the start lifecycle to - * register a custom component in the Ingest package config. - */ -export function registerPackageConfigComponent( - key: AllowedPackageKey, - value: CustomConfigurePackageConfigContent -) { - PackageConfigMapping[key] = value; -} - -const EmptyPackageConfig: CustomConfigurePackageConfigContent = () => ( - -

- -

- - } - /> -); - -export const CustomPackageConfig = (props: CustomConfigurePackageConfigProps) => { - const CustomPackageConfigContent = PackageConfigMapping[props.packageName] || EmptyPackageConfig; - return ; -}; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/index.ts b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/index.ts deleted file mode 100644 index e53206c68c4432..00000000000000 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/index.ts +++ /dev/null @@ -1,8 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -export { PackageConfigsTable } from './package_configs/package_configs_table'; -export { ConfigPackageConfigsView } from './package_configs'; -export { ConfigSettingsView } from './settings'; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/package_configs/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/package_configs/index.tsx deleted file mode 100644 index 3aef297e8d22eb..00000000000000 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/package_configs/index.tsx +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import React, { memo } from 'react'; -import { AgentConfig, PackageConfig } from '../../../../../types'; -import { NoPackageConfigs } from './no_package_configs'; -import { PackageConfigsTable } from './package_configs_table'; - -export const ConfigPackageConfigsView = memo<{ config: AgentConfig }>(({ config }) => { - if (config.package_configs.length === 0) { - return ; - } - - return ( - - ); -}); diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/index.tsx deleted file mode 100644 index 727ef233472516..00000000000000 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/index.tsx +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -import React from 'react'; -import { HashRouter as Router, Switch, Route } from 'react-router-dom'; -import { PAGE_ROUTING_PATHS } from '../../constants'; -import { useBreadcrumbs } from '../../hooks'; -import { AgentConfigListPage } from './list_page'; -import { AgentConfigDetailsPage } from './details_page'; -import { CreatePackageConfigPage } from './create_package_config_page'; -import { EditPackageConfigPage } from './edit_package_config_page'; - -export const AgentConfigApp: React.FunctionComponent = () => { - useBreadcrumbs('configurations'); - - return ( - - - - - - - - - - - - - - - - - ); -}; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/actions_menu.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/components/actions_menu.tsx similarity index 74% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/actions_menu.tsx rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/components/actions_menu.tsx index a71de4b60c08cf..691de5f259134f 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/actions_menu.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/components/actions_menu.tsx @@ -6,22 +6,22 @@ import React, { memo, useState, useMemo } from 'react'; import { FormattedMessage } from '@kbn/i18n/react'; import { EuiContextMenuItem, EuiPortal } from '@elastic/eui'; -import { AgentConfig } from '../../../types'; +import { AgentPolicy } from '../../../types'; import { useCapabilities } from '../../../hooks'; import { ContextMenuActions } from '../../../components'; import { AgentEnrollmentFlyout } from '../../fleet/components'; -import { ConfigYamlFlyout } from './config_yaml_flyout'; -import { AgentConfigCopyProvider } from './config_copy_provider'; +import { AgentPolicyYamlFlyout } from './agent_policy_yaml_flyout'; +import { AgentPolicyCopyProvider } from './agent_policy_copy_provider'; -export const AgentConfigActionMenu = memo<{ - config: AgentConfig; - onCopySuccess?: (newAgentConfig: AgentConfig) => void; +export const AgentPolicyActionMenu = memo<{ + agentPolicy: AgentPolicy; + onCopySuccess?: (newAgentPolicy: AgentPolicy) => void; fullButton?: boolean; enrollmentFlyoutOpenByDefault?: boolean; onCancelEnrollment?: () => void; }>( ({ - config, + agentPolicy, onCopySuccess, fullButton = false, enrollmentFlyoutOpenByDefault = false, @@ -42,21 +42,21 @@ export const AgentConfigActionMenu = memo<{ }, [onCancelEnrollment, setIsEnrollmentFlyoutOpen]); return ( - - {(copyAgentConfigPrompt) => { + + {(copyAgentPolicyPrompt) => { return ( <> {isYamlFlyoutOpen ? ( - setIsYamlFlyoutOpen(false)} /> ) : null} {isEnrollmentFlyoutOpen && ( - + )} ), @@ -84,31 +84,31 @@ export const AgentConfigActionMenu = memo<{ key="enrollAgents" > , setIsYamlFlyoutOpen(!isYamlFlyoutOpen)} - key="viewConfig" + key="viewPolicy" > , { - copyAgentConfigPrompt(config, onCopySuccess); + copyAgentPolicyPrompt(agentPolicy, onCopySuccess); }} - key="copyConfig" + key="copyPolicy" > , ]} @@ -116,7 +116,7 @@ export const AgentConfigActionMenu = memo<{ ); }} - + ); } ); diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/config_copy_provider.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/components/agent_policy_copy_provider.tsx similarity index 54% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/config_copy_provider.tsx rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/components/agent_policy_copy_provider.tsx index c1bd0846b887e6..8a91cabe78d00f 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/config_copy_provider.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/components/agent_policy_copy_provider.tsx @@ -8,63 +8,63 @@ import React, { Fragment, useRef, useState } from 'react'; import { EuiConfirmModal, EuiOverlayMask, EuiFormRow, EuiFieldText } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; -import { AgentConfig } from '../../../types'; -import { sendCopyAgentConfig, useCore } from '../../../hooks'; +import { AgentPolicy } from '../../../types'; +import { sendCopyAgentPolicy, useCore } from '../../../hooks'; interface Props { - children: (copyAgentConfig: CopyAgentConfig) => React.ReactElement; + children: (copyAgentPolicy: CopyAgentPolicy) => React.ReactElement; } -export type CopyAgentConfig = (agentConfig: AgentConfig, onSuccess?: OnSuccessCallback) => void; +export type CopyAgentPolicy = (agentPolicy: AgentPolicy, onSuccess?: OnSuccessCallback) => void; -type OnSuccessCallback = (newAgentConfig: AgentConfig) => void; +type OnSuccessCallback = (newAgentPolicy: AgentPolicy) => void; -export const AgentConfigCopyProvider: React.FunctionComponent = ({ children }) => { +export const AgentPolicyCopyProvider: React.FunctionComponent = ({ children }) => { const { notifications } = useCore(); - const [agentConfig, setAgentConfig] = useState(); - const [newAgentConfig, setNewAgentConfig] = useState>(); + const [agentPolicy, setAgentPolicy] = useState(); + const [newAgentPolicy, setNewAgentPolicy] = useState>(); const [isModalOpen, setIsModalOpen] = useState(false); const [isLoading, setIsLoading] = useState(false); const onSuccessCallback = useRef(null); - const copyAgentConfigPrompt: CopyAgentConfig = ( - agentConfigToCopy, + const copyAgentPolicyPrompt: CopyAgentPolicy = ( + agentPolicyToCopy, onSuccess = () => undefined ) => { - if (!agentConfigToCopy) { - throw new Error('No agent config specified to copy'); + if (!agentPolicyToCopy) { + throw new Error('No agent policy specified to copy'); } setIsModalOpen(true); - setAgentConfig(agentConfigToCopy); - setNewAgentConfig({ + setAgentPolicy(agentPolicyToCopy); + setNewAgentPolicy({ name: i18n.translate( - 'xpack.ingestManager.copyAgentConfig.confirmModal.defaultNewConfigName', + 'xpack.ingestManager.copyAgentPolicy.confirmModal.defaultNewPolicyName', { defaultMessage: '{name} (copy)', - values: { name: agentConfigToCopy.name }, + values: { name: agentPolicyToCopy.name }, } ), - description: agentConfigToCopy.description, + description: agentPolicyToCopy.description, }); onSuccessCallback.current = onSuccess; }; const closeModal = () => { - setAgentConfig(undefined); - setNewAgentConfig(undefined); + setAgentPolicy(undefined); + setNewAgentPolicy(undefined); setIsLoading(false); setIsModalOpen(false); }; - const copyAgentConfig = async () => { + const copyAgentPolicy = async () => { setIsLoading(true); try { - const { data } = await sendCopyAgentConfig(agentConfig!.id, newAgentConfig!); + const { data } = await sendCopyAgentPolicy(agentPolicy!.id, newAgentPolicy!); if (data?.success) { notifications.toasts.addSuccess( - i18n.translate('xpack.ingestManager.copyAgentConfig.successNotificationTitle', { - defaultMessage: 'Agent config copied', + i18n.translate('xpack.ingestManager.copyAgentPolicy.successNotificationTitle', { + defaultMessage: 'Agent policy copied', }) ); if (onSuccessCallback.current) { @@ -74,16 +74,16 @@ export const AgentConfigCopyProvider: React.FunctionComponent = ({ childr if (!data?.success) { notifications.toasts.addDanger( - i18n.translate('xpack.ingestManager.copyAgentConfig.failureNotificationTitle', { - defaultMessage: "Error copying agent config '{id}'", - values: { id: agentConfig!.id }, + i18n.translate('xpack.ingestManager.copyAgentPolicy.failureNotificationTitle', { + defaultMessage: "Error copying agent policy '{id}'", + values: { id: agentPolicy!.id }, }) ); } } catch (e) { notifications.toasts.addDanger( - i18n.translate('xpack.ingestManager.copyAgentConfig.fatalErrorNotificationTitle', { - defaultMessage: 'Error copying agent config', + i18n.translate('xpack.ingestManager.copyAgentPolicy.fatalErrorNotificationTitle', { + defaultMessage: 'Error copying agent policy', }) ); } @@ -91,7 +91,7 @@ export const AgentConfigCopyProvider: React.FunctionComponent = ({ childr }; const renderModal = () => { - if (!isModalOpen || !agentConfig || !newAgentConfig) { + if (!isModalOpen || !agentPolicy || !newAgentPolicy) { return null; } @@ -101,55 +101,55 @@ export const AgentConfigCopyProvider: React.FunctionComponent = ({ childr title={ } onCancel={closeModal} - onConfirm={copyAgentConfig} + onConfirm={copyAgentPolicy} cancelButtonText={ } confirmButtonText={ } - confirmButtonDisabled={isLoading || !newAgentConfig.name.trim()} + confirmButtonDisabled={isLoading || !newAgentPolicy.name.trim()} >

} fullWidth > setNewAgentConfig({ ...newAgentConfig, name: e.target.value })} + value={newAgentPolicy.name} + onChange={(e) => setNewAgentPolicy({ ...newAgentPolicy, name: e.target.value })} /> } @@ -157,9 +157,9 @@ export const AgentConfigCopyProvider: React.FunctionComponent = ({ childr > - setNewAgentConfig({ ...newAgentConfig, description: e.target.value }) + setNewAgentPolicy({ ...newAgentPolicy, description: e.target.value }) } /> @@ -170,7 +170,7 @@ export const AgentConfigCopyProvider: React.FunctionComponent = ({ childr return ( - {children(copyAgentConfigPrompt)} + {children(copyAgentPolicyPrompt)} {renderModal()} ); diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/config_delete_provider.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/components/agent_policy_delete_provider.tsx similarity index 62% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/config_delete_provider.tsx rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/components/agent_policy_delete_provider.tsx index d517dde45d5e3c..08367bf2a97bfc 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/config_delete_provider.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/components/agent_policy_delete_provider.tsx @@ -9,87 +9,87 @@ import { EuiConfirmModal, EuiOverlayMask, EuiCallOut } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; import { AGENT_SAVED_OBJECT_TYPE } from '../../../constants'; -import { sendDeleteAgentConfig, useCore, useConfig, sendRequest } from '../../../hooks'; +import { sendDeleteAgentPolicy, useCore, useConfig, sendRequest } from '../../../hooks'; interface Props { - children: (deleteAgentConfig: DeleteAgentConfig) => React.ReactElement; + children: (deleteAgentPolicy: DeleteAgentPolicy) => React.ReactElement; } -export type DeleteAgentConfig = (agentConfig: string, onSuccess?: OnSuccessCallback) => void; +export type DeleteAgentPolicy = (agentPolicy: string, onSuccess?: OnSuccessCallback) => void; -type OnSuccessCallback = (agentConfigDeleted: string) => void; +type OnSuccessCallback = (agentPolicyDeleted: string) => void; -export const AgentConfigDeleteProvider: React.FunctionComponent = ({ children }) => { +export const AgentPolicyDeleteProvider: React.FunctionComponent = ({ children }) => { const { notifications } = useCore(); const { fleet: { enabled: isFleetEnabled }, } = useConfig(); - const [agentConfig, setAgentConfig] = useState(); + const [agentPolicy, setAgentPolicy] = useState(); const [isModalOpen, setIsModalOpen] = useState(false); const [isLoadingAgentsCount, setIsLoadingAgentsCount] = useState(false); const [agentsCount, setAgentsCount] = useState(0); const [isLoading, setIsLoading] = useState(false); const onSuccessCallback = useRef(null); - const deleteAgentConfigPrompt: DeleteAgentConfig = ( - agentConfigToDelete, + const deleteAgentPolicyPrompt: DeleteAgentPolicy = ( + agentPolicyToDelete, onSuccess = () => undefined ) => { - if (!agentConfigToDelete) { - throw new Error('No agent config specified for deletion'); + if (!agentPolicyToDelete) { + throw new Error('No agent policy specified for deletion'); } setIsModalOpen(true); - setAgentConfig(agentConfigToDelete); - fetchAgentsCount(agentConfigToDelete); + setAgentPolicy(agentPolicyToDelete); + fetchAgentsCount(agentPolicyToDelete); onSuccessCallback.current = onSuccess; }; const closeModal = () => { - setAgentConfig(undefined); + setAgentPolicy(undefined); setIsLoading(false); setIsLoadingAgentsCount(false); setIsModalOpen(false); }; - const deleteAgentConfig = async () => { + const deleteAgentPolicy = async () => { setIsLoading(true); try { - const { data } = await sendDeleteAgentConfig({ - agentConfigId: agentConfig!, + const { data } = await sendDeleteAgentPolicy({ + agentPolicyId: agentPolicy!, }); if (data?.success) { notifications.toasts.addSuccess( - i18n.translate('xpack.ingestManager.deleteAgentConfig.successSingleNotificationTitle', { - defaultMessage: "Deleted agent config '{id}'", - values: { id: agentConfig }, + i18n.translate('xpack.ingestManager.deleteAgentPolicy.successSingleNotificationTitle', { + defaultMessage: "Deleted agent policy '{id}'", + values: { id: agentPolicy }, }) ); if (onSuccessCallback.current) { - onSuccessCallback.current(agentConfig!); + onSuccessCallback.current(agentPolicy!); } } if (!data?.success) { notifications.toasts.addDanger( - i18n.translate('xpack.ingestManager.deleteAgentConfig.failureSingleNotificationTitle', { - defaultMessage: "Error deleting agent config '{id}'", - values: { id: agentConfig }, + i18n.translate('xpack.ingestManager.deleteAgentPolicy.failureSingleNotificationTitle', { + defaultMessage: "Error deleting agent policy '{id}'", + values: { id: agentPolicy }, }) ); } } catch (e) { notifications.toasts.addDanger( - i18n.translate('xpack.ingestManager.deleteAgentConfig.fatalErrorNotificationTitle', { - defaultMessage: 'Error deleting agent config', + i18n.translate('xpack.ingestManager.deleteAgentPolicy.fatalErrorNotificationTitle', { + defaultMessage: 'Error deleting agent policy', }) ); } closeModal(); }; - const fetchAgentsCount = async (agentConfigToCheck: string) => { + const fetchAgentsCount = async (agentPolicyToCheck: string) => { if (!isFleetEnabled || isLoadingAgentsCount) { return; } @@ -98,7 +98,7 @@ export const AgentConfigDeleteProvider: React.FunctionComponent = ({ chil path: `/api/ingest_manager/fleet/agents`, method: 'get', query: { - kuery: `${AGENT_SAVED_OBJECT_TYPE}.config_id : ${agentConfigToCheck}`, + kuery: `${AGENT_SAVED_OBJECT_TYPE}.policy_id : ${agentPolicyToCheck}`, }, }); setAgentsCount(data?.total || 0); @@ -115,28 +115,28 @@ export const AgentConfigDeleteProvider: React.FunctionComponent = ({ chil } onCancel={closeModal} - onConfirm={deleteAgentConfig} + onConfirm={deleteAgentPolicy} cancelButtonText={ } confirmButtonText={ isLoading || isLoadingAgentsCount ? ( ) : ( ) } @@ -145,22 +145,22 @@ export const AgentConfigDeleteProvider: React.FunctionComponent = ({ chil > {isLoadingAgentsCount ? ( ) : agentsCount ? ( = ({ chil ) : ( )} @@ -179,7 +179,7 @@ export const AgentConfigDeleteProvider: React.FunctionComponent = ({ chil return ( - {children(deleteAgentConfigPrompt)} + {children(deleteAgentPolicyPrompt)} {renderModal()} ); diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/config_form.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/components/agent_policy_form.tsx similarity index 70% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/config_form.tsx rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/components/agent_policy_form.tsx index b60c36b282a0d3..a858a53c485b7f 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/config_form.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/components/agent_policy_form.tsx @@ -23,8 +23,8 @@ import { import { FormattedMessage } from '@kbn/i18n/react'; import { i18n } from '@kbn/i18n'; import styled from 'styled-components'; -import { NewAgentConfig, AgentConfig } from '../../../types'; -import { AgentConfigDeleteProvider } from './config_delete_provider'; +import { NewAgentPolicy, AgentPolicy } from '../../../types'; +import { AgentPolicyDeleteProvider } from './agent_policy_delete_provider'; interface ValidationResults { [key: string]: JSX.Element[]; @@ -36,24 +36,24 @@ const StyledEuiAccordion = styled(EuiAccordion)` } `; -export const agentConfigFormValidation = ( - agentConfig: Partial +export const agentPolicyFormValidation = ( + agentPolicy: Partial ): ValidationResults => { const errors: ValidationResults = {}; - if (!agentConfig.name?.trim()) { + if (!agentPolicy.name?.trim()) { errors.name = [ , ]; } - if (!agentConfig.namespace?.trim()) { + if (!agentPolicy.namespace?.trim()) { errors.namespace = [ , ]; @@ -63,8 +63,8 @@ export const agentConfigFormValidation = ( }; interface Props { - agentConfig: Partial; - updateAgentConfig: (u: Partial) => void; + agentPolicy: Partial; + updateAgentPolicy: (u: Partial) => void; withSysMonitoring: boolean; updateSysMonitoring: (newValue: boolean) => void; validation: ValidationResults; @@ -72,9 +72,9 @@ interface Props { onDelete?: () => void; } -export const AgentConfigForm: React.FunctionComponent = ({ - agentConfig, - updateAgentConfig, +export const AgentPolicyForm: React.FunctionComponent = ({ + agentPolicy, + updateAgentPolicy, withSysMonitoring, updateSysMonitoring, validation, @@ -92,11 +92,11 @@ export const AgentConfigForm: React.FunctionComponent = ({ name: 'name', label: ( ), - placeholder: i18n.translate('xpack.ingestManager.agentConfigForm.nameFieldPlaceholder', { + placeholder: i18n.translate('xpack.ingestManager.agentPolicyForm.nameFieldPlaceholder', { defaultMessage: 'Choose a name', }), }, @@ -104,14 +104,14 @@ export const AgentConfigForm: React.FunctionComponent = ({ name: 'description', label: ( ), placeholder: i18n.translate( - 'xpack.ingestManager.agentConfigForm.descriptionFieldPlaceholder', + 'xpack.ingestManager.agentPolicyForm.descriptionFieldPlaceholder', { - defaultMessage: 'How will this configuration be used?', + defaultMessage: 'How will this policy be used?', } ), }, @@ -123,15 +123,15 @@ export const AgentConfigForm: React.FunctionComponent = ({ title={

} description={ } > @@ -150,8 +150,8 @@ export const AgentConfigForm: React.FunctionComponent = ({ > updateAgentConfig({ [name]: e.target.value })} + value={agentPolicy[name]} + onChange={(e) => updateAgentPolicy({ [name]: e.target.value })} isInvalid={Boolean(touchedFields[name] && validation[name])} onBlur={() => setTouchedFields({ ...touchedFields, [name]: true })} placeholder={placeholder} @@ -166,15 +166,15 @@ export const AgentConfigForm: React.FunctionComponent = ({ title={

} description={ } > @@ -187,12 +187,12 @@ export const AgentConfigForm: React.FunctionComponent = ({ fullWidth singleSelection noSuggestions - selectedOptions={agentConfig.namespace ? [{ label: agentConfig.namespace }] : []} + selectedOptions={agentPolicy.namespace ? [{ label: agentPolicy.namespace }] : []} onCreateOption={(value: string) => { - updateAgentConfig({ namespace: value }); + updateAgentPolicy({ namespace: value }); }} onChange={(selectedOptions) => { - updateAgentConfig({ + updateAgentPolicy({ namespace: (selectedOptions.length ? selectedOptions[0] : '') as string, }); }} @@ -205,14 +205,14 @@ export const AgentConfigForm: React.FunctionComponent = ({ title={

} description={ } @@ -224,15 +224,14 @@ export const AgentConfigForm: React.FunctionComponent = ({ label: ( <> {' '} = ({ label: ( <> {' '} = ({ ), }, ]} - idToSelectedMap={(agentConfig.monitoring_enabled || []).reduce( + idToSelectedMap={(agentPolicy.monitoring_enabled || []).reduce( (acc: { logs: boolean; metrics: boolean }, key) => { acc[key] = true; return acc; @@ -279,10 +277,10 @@ export const AgentConfigForm: React.FunctionComponent = ({ } const hasLogs = - agentConfig.monitoring_enabled && agentConfig.monitoring_enabled.indexOf(id) >= 0; + agentPolicy.monitoring_enabled && agentPolicy.monitoring_enabled.indexOf(id) >= 0; - const previousValues = agentConfig.monitoring_enabled || []; - updateAgentConfig({ + const previousValues = agentPolicy.monitoring_enabled || []; + updateAgentPolicy({ monitoring_enabled: hasLogs ? previousValues.filter((type) => type !== id) : [...previousValues, id], @@ -290,46 +288,46 @@ export const AgentConfigForm: React.FunctionComponent = ({ }} /> - {isEditing && 'id' in agentConfig ? ( + {isEditing && 'id' in agentPolicy ? ( } description={ <> - - {(deleteAgentConfigPrompt) => { + + {(deleteAgentPolicyPrompt) => { return ( deleteAgentConfigPrompt(agentConfig.id!, onDelete)} + disabled={Boolean(agentPolicy.is_default)} + onClick={() => deleteAgentPolicyPrompt(agentPolicy.id!, onDelete)} > ); }} - - {agentConfig.is_default ? ( + + {agentPolicy.is_default ? ( <> @@ -348,25 +346,25 @@ export const AgentConfigForm: React.FunctionComponent = ({ } > {' '} = ({ id="advancedOptions" buttonContent={ } diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/config_yaml_flyout.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/components/agent_policy_yaml_flyout.tsx similarity index 68% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/config_yaml_flyout.tsx rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/components/agent_policy_yaml_flyout.tsx index 9c2d09b02665f2..919bb49f69aaee 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/config_yaml_flyout.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/components/agent_policy_yaml_flyout.tsx @@ -19,9 +19,9 @@ import { EuiButtonEmpty, EuiButton, } from '@elastic/eui'; -import { useGetOneAgentConfigFull, useGetOneAgentConfig, useCore } from '../../../hooks'; +import { useGetOneAgentPolicyFull, useGetOneAgentPolicy, useCore } from '../../../hooks'; import { Loading } from '../../../components'; -import { configToYaml, agentConfigRouteService } from '../../../services'; +import { fullAgentPolicyToYaml, agentPolicyRouteService } from '../../../services'; const FlyoutBody = styled(EuiFlyoutBody)` .euiFlyoutBody__overflowContent { @@ -29,40 +29,40 @@ const FlyoutBody = styled(EuiFlyoutBody)` } `; -export const ConfigYamlFlyout = memo<{ configId: string; onClose: () => void }>( - ({ configId, onClose }) => { +export const AgentPolicyYamlFlyout = memo<{ policyId: string; onClose: () => void }>( + ({ policyId, onClose }) => { const core = useCore(); - const { isLoading: isLoadingYaml, data: yamlData } = useGetOneAgentConfigFull(configId); - const { data: configData } = useGetOneAgentConfig(configId); + const { isLoading: isLoadingYaml, data: yamlData } = useGetOneAgentPolicyFull(policyId); + const { data: agentPolicyData } = useGetOneAgentPolicy(policyId); const body = isLoadingYaml && !yamlData ? ( ) : ( - {configToYaml(yamlData!.item)} + {fullAgentPolicyToYaml(yamlData!.item)} ); const downloadLink = core.http.basePath.prepend( - agentConfigRouteService.getInfoFullDownloadPath(configId) + agentPolicyRouteService.getInfoFullDownloadPath(policyId) ); return ( - + -

- {configData?.item ? ( +

+ {agentPolicyData?.item ? ( ) : ( )}

@@ -74,7 +74,7 @@ export const ConfigYamlFlyout = memo<{ configId: string; onClose: () => void }>( @@ -86,8 +86,8 @@ export const ConfigYamlFlyout = memo<{ configId: string; onClose: () => void }>( isDisabled={Boolean(isLoadingYaml && !yamlData)} > diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/confirm_deploy_modal.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/components/confirm_deploy_modal.tsx similarity index 72% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/confirm_deploy_modal.tsx rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/components/confirm_deploy_modal.tsx index 51f37f72a75145..d1a9b4812bfe0e 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/confirm_deploy_modal.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/components/confirm_deploy_modal.tsx @@ -8,20 +8,20 @@ import React from 'react'; import { EuiCallOut, EuiOverlayMask, EuiConfirmModal, EuiSpacer } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; import { i18n } from '@kbn/i18n'; -import { AgentConfig } from '../../../types'; +import { AgentPolicy } from '../../../types'; -export const ConfirmDeployConfigModal: React.FunctionComponent<{ +export const ConfirmDeployAgentPolicyModal: React.FunctionComponent<{ onConfirm: () => void; onCancel: () => void; agentCount: number; - agentConfig: AgentConfig; -}> = ({ onConfirm, onCancel, agentCount, agentConfig }) => { + agentPolicy: AgentPolicy; +}> = ({ onConfirm, onCancel, agentCount, agentPolicy }) => { return ( } @@ -29,13 +29,13 @@ export const ConfirmDeployConfigModal: React.FunctionComponent<{ onConfirm={onConfirm} cancelButtonText={ } confirmButtonText={ } @@ -43,7 +43,7 @@ export const ConfirmDeployConfigModal: React.FunctionComponent<{ >
{agentConfig.name}, + policyName: {agentPolicy.name}, }} />
diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/danger_eui_context_menu_item.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/components/danger_eui_context_menu_item.tsx similarity index 100% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/danger_eui_context_menu_item.tsx rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/components/danger_eui_context_menu_item.tsx diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/components/index.ts b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/components/index.ts new file mode 100644 index 00000000000000..1ec43f4df8c8ea --- /dev/null +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/components/index.ts @@ -0,0 +1,14 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +export { AgentPolicyForm, agentPolicyFormValidation } from './agent_policy_form'; +export { AgentPolicyCopyProvider } from './agent_policy_copy_provider'; +export { AgentPolicyDeleteProvider } from './agent_policy_delete_provider'; +export { PackagePolicyDeleteProvider } from './package_policy_delete_provider'; +export { AgentPolicyYamlFlyout } from './agent_policy_yaml_flyout'; +export { LinkedAgentCount } from './linked_agent_count'; +export { ConfirmDeployAgentPolicyModal } from './confirm_deploy_modal'; +export { DangerEuiContextMenuItem } from './danger_eui_context_menu_item'; +export { AgentPolicyActionMenu } from './actions_menu'; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/linked_agent_count.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/components/linked_agent_count.tsx similarity index 77% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/linked_agent_count.tsx rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/components/linked_agent_count.tsx index 8294597e43c500..72e60ae678739b 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/linked_agent_count.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/components/linked_agent_count.tsx @@ -10,12 +10,12 @@ import { EuiLink } from '@elastic/eui'; import { useLink } from '../../../hooks'; import { AGENT_SAVED_OBJECT_TYPE } from '../../../constants'; -export const LinkedAgentCount = memo<{ count: number; agentConfigId: string }>( - ({ count, agentConfigId }) => { +export const LinkedAgentCount = memo<{ count: number; agentPolicyId: string }>( + ({ count, agentPolicyId }) => { const { getHref } = useLink(); const displayValue = ( @@ -23,7 +23,7 @@ export const LinkedAgentCount = memo<{ count: number; agentConfigId: string }>( return count > 0 ? ( {displayValue} diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/package_config_delete_provider.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/components/package_policy_delete_provider.tsx similarity index 70% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/package_config_delete_provider.tsx rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/components/package_policy_delete_provider.tsx index 3421b70715c351..3a6852de873f8b 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/package_config_delete_provider.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/components/package_policy_delete_provider.tsx @@ -8,31 +8,31 @@ import React, { Fragment, useMemo, useRef, useState } from 'react'; import { EuiCallOut, EuiConfirmModal, EuiOverlayMask, EuiSpacer } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; -import { useCore, sendRequest, sendDeletePackageConfig, useConfig } from '../../../hooks'; +import { useCore, sendRequest, sendDeletePackagePolicy, useConfig } from '../../../hooks'; import { AGENT_API_ROUTES, AGENT_SAVED_OBJECT_TYPE } from '../../../constants'; -import { AgentConfig } from '../../../types'; +import { AgentPolicy } from '../../../types'; interface Props { - agentConfig: AgentConfig; - children: (deletePackageConfigsPrompt: DeletePackageConfigsPrompt) => React.ReactElement; + agentPolicy: AgentPolicy; + children: (deletePackagePoliciesPrompt: DeletePackagePoliciesPrompt) => React.ReactElement; } -export type DeletePackageConfigsPrompt = ( - packageConfigsToDelete: string[], +export type DeletePackagePoliciesPrompt = ( + packagePoliciesToDelete: string[], onSuccess?: OnSuccessCallback ) => void; -type OnSuccessCallback = (packageConfigsDeleted: string[]) => void; +type OnSuccessCallback = (packagePoliciesDeleted: string[]) => void; -export const PackageConfigDeleteProvider: React.FunctionComponent = ({ - agentConfig, +export const PackagePolicyDeleteProvider: React.FunctionComponent = ({ + agentPolicy, children, }) => { const { notifications } = useCore(); const { fleet: { enabled: isFleetEnabled }, } = useConfig(); - const [packageConfigs, setPackageConfigs] = useState([]); + const [packagePolicies, setPackagePolicies] = useState([]); const [isModalOpen, setIsModalOpen] = useState(false); const [isLoadingAgentsCount, setIsLoadingAgentsCount] = useState(false); const [agentsCount, setAgentsCount] = useState(0); @@ -51,22 +51,22 @@ export const PackageConfigDeleteProvider: React.FunctionComponent = ({ query: { page: 1, perPage: 1, - kuery: `${AGENT_SAVED_OBJECT_TYPE}.config_id : ${agentConfig.id}`, + kuery: `${AGENT_SAVED_OBJECT_TYPE}.policy_id : ${agentPolicy.id}`, }, }); setAgentsCount(data?.total || 0); setIsLoadingAgentsCount(false); }, - [agentConfig.id, isFleetEnabled, isLoadingAgentsCount] + [agentPolicy.id, isFleetEnabled, isLoadingAgentsCount] ); - const deletePackageConfigsPrompt = useMemo( - (): DeletePackageConfigsPrompt => (packageConfigsToDelete, onSuccess = () => undefined) => { - if (!Array.isArray(packageConfigsToDelete) || packageConfigsToDelete.length === 0) { - throw new Error('No package configs specified for deletion'); + const deletePackagePoliciesPrompt = useMemo( + (): DeletePackagePoliciesPrompt => (packagePoliciesToDelete, onSuccess = () => undefined) => { + if (!Array.isArray(packagePoliciesToDelete) || packagePoliciesToDelete.length === 0) { + throw new Error('No package policies specified for deletion'); } setIsModalOpen(true); - setPackageConfigs(packageConfigsToDelete); + setPackagePolicies(packagePoliciesToDelete); fetchAgentsCount(); onSuccessCallback.current = onSuccess; }, @@ -75,7 +75,7 @@ export const PackageConfigDeleteProvider: React.FunctionComponent = ({ const closeModal = useMemo( () => () => { - setPackageConfigs([]); + setPackagePolicies([]); setIsLoading(false); setIsLoadingAgentsCount(false); setIsModalOpen(false); @@ -83,12 +83,12 @@ export const PackageConfigDeleteProvider: React.FunctionComponent = ({ [] ); - const deletePackageConfigs = useMemo( + const deletePackagePolicies = useMemo( () => async () => { setIsLoading(true); try { - const { data } = await sendDeletePackageConfig({ packageConfigIds: packageConfigs }); + const { data } = await sendDeletePackagePolicy({ packagePolicyIds: packagePolicies }); const successfulResults = data?.filter((result) => result.success) || []; const failedResults = data?.filter((result) => !result.success) || []; @@ -96,14 +96,14 @@ export const PackageConfigDeleteProvider: React.FunctionComponent = ({ const hasMultipleSuccesses = successfulResults.length > 1; const successMessage = hasMultipleSuccesses ? i18n.translate( - 'xpack.ingestManager.deletePackageConfig.successMultipleNotificationTitle', + 'xpack.ingestManager.deletePackagePolicy.successMultipleNotificationTitle', { defaultMessage: 'Deleted {count} integrations', values: { count: successfulResults.length }, } ) : i18n.translate( - 'xpack.ingestManager.deletePackageConfig.successSingleNotificationTitle', + 'xpack.ingestManager.deletePackagePolicy.successSingleNotificationTitle', { defaultMessage: "Deleted integration '{id}'", values: { id: successfulResults[0].id }, @@ -116,14 +116,14 @@ export const PackageConfigDeleteProvider: React.FunctionComponent = ({ const hasMultipleFailures = failedResults.length > 1; const failureMessage = hasMultipleFailures ? i18n.translate( - 'xpack.ingestManager.deletePackageConfig.failureMultipleNotificationTitle', + 'xpack.ingestManager.deletePackagePolicy.failureMultipleNotificationTitle', { defaultMessage: 'Error deleting {count} integrations', values: { count: failedResults.length }, } ) : i18n.translate( - 'xpack.ingestManager.deletePackageConfig.failureSingleNotificationTitle', + 'xpack.ingestManager.deletePackagePolicy.failureSingleNotificationTitle', { defaultMessage: "Error deleting integration '{id}'", values: { id: failedResults[0].id }, @@ -137,14 +137,14 @@ export const PackageConfigDeleteProvider: React.FunctionComponent = ({ } } catch (e) { notifications.toasts.addDanger( - i18n.translate('xpack.ingestManager.deletePackageConfig.fatalErrorNotificationTitle', { + i18n.translate('xpack.ingestManager.deletePackagePolicy.fatalErrorNotificationTitle', { defaultMessage: 'Error deleting integration', }) ); } closeModal(); }, - [closeModal, packageConfigs, notifications.toasts] + [closeModal, packagePolicies, notifications.toasts] ); const renderModal = () => { @@ -157,31 +157,31 @@ export const PackageConfigDeleteProvider: React.FunctionComponent = ({ } onCancel={closeModal} - onConfirm={deletePackageConfigs} + onConfirm={deletePackagePolicies} cancelButtonText={ } confirmButtonText={ isLoading || isLoadingAgentsCount ? ( ) : ( ) @@ -191,7 +191,7 @@ export const PackageConfigDeleteProvider: React.FunctionComponent = ({ > {isLoadingAgentsCount ? ( ) : agentsCount ? ( @@ -200,17 +200,17 @@ export const PackageConfigDeleteProvider: React.FunctionComponent = ({ color="danger" title={ } > {agentConfig.name}, + agentPolicyName: {agentPolicy.name}, }} /> @@ -219,7 +219,7 @@ export const PackageConfigDeleteProvider: React.FunctionComponent = ({ ) : null} {!isLoadingAgentsCount && ( )} @@ -230,7 +230,7 @@ export const PackageConfigDeleteProvider: React.FunctionComponent = ({ return ( - {children(deletePackageConfigsPrompt)} + {children(deletePackagePoliciesPrompt)} {renderModal()} ); diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/components/custom_package_policy.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/components/custom_package_policy.tsx new file mode 100644 index 00000000000000..47c14ce0a3e811 --- /dev/null +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/components/custom_package_policy.tsx @@ -0,0 +1,61 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import React from 'react'; +import { FormattedMessage } from '@kbn/i18n/react'; +import { EuiEmptyPrompt, EuiText } from '@elastic/eui'; +import { NewPackagePolicy } from '../../../../types'; +import { CreatePackagePolicyFrom } from '../types'; + +export interface CustomConfigurePackagePolicyProps { + packageName: string; + from: CreatePackagePolicyFrom; + packagePolicy: NewPackagePolicy; + packagePolicyId?: string; +} + +/** + * Custom content type that external plugins can provide to Ingest's + * package policy UI. + */ +export type CustomConfigurePackagePolicyContent = React.FC; + +type AllowedPackageKey = 'endpoint'; +const PackagePolicyMapping: { + [key: string]: CustomConfigurePackagePolicyContent; +} = {}; + +/** + * Plugins can call this function from the start lifecycle to + * register a custom component in the Ingest package policy. + */ +export function registerPackagePolicyComponent( + key: AllowedPackageKey, + value: CustomConfigurePackagePolicyContent +) { + PackagePolicyMapping[key] = value; +} + +const EmptyPackagePolicy: CustomConfigurePackagePolicyContent = () => ( + +

+ +

+ + } + /> +); + +export const CustomPackagePolicy = (props: CustomConfigurePackagePolicyProps) => { + const CustomPackagePolicyContent = PackagePolicyMapping[props.packageName] || EmptyPackagePolicy; + return ; +}; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/components/index.ts b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/components/index.ts similarity index 51% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/components/index.ts rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/components/index.ts index e8d2ef329b25ef..893ed00cca9ac3 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/components/index.ts +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/components/index.ts @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -export { CreatePackageConfigPageLayout } from './layout'; -export { PackageConfigInputPanel } from './package_config_input_panel'; -export { PackageConfigInputVarField } from './package_config_input_var_field'; -export { CustomPackageConfig } from './custom_package_config'; +export { CreatePackagePolicyPageLayout } from './layout'; +export { PackagePolicyInputPanel } from './package_policy_input_panel'; +export { PackagePolicyInputVarField } from './package_policy_input_var_field'; +export { CustomPackagePolicy } from './custom_package_policy'; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/components/layout.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/components/layout.tsx similarity index 79% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/components/layout.tsx rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/components/layout.tsx index 8316e2500453a5..3bcf0aab9a5c83 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/components/layout.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/components/layout.tsx @@ -16,15 +16,15 @@ import { EuiSpacer, } from '@elastic/eui'; import { WithHeaderLayout } from '../../../../layouts'; -import { AgentConfig, PackageInfo } from '../../../../types'; +import { AgentPolicy, PackageInfo } from '../../../../types'; import { PackageIcon } from '../../../../components/package_icon'; -import { CreatePackageConfigFrom } from '../types'; +import { CreatePackagePolicyFrom } from '../types'; -export const CreatePackageConfigPageLayout: React.FunctionComponent<{ - from: CreatePackageConfigFrom; +export const CreatePackagePolicyPageLayout: React.FunctionComponent<{ + from: CreatePackagePolicyFrom; cancelUrl: string; onCancel?: React.ReactEventHandler; - agentConfig?: AgentConfig; + agentPolicy?: AgentPolicy; packageInfo?: PackageInfo; 'data-test-subj'?: string; }> = memo( @@ -32,7 +32,7 @@ export const CreatePackageConfigPageLayout: React.FunctionComponent<{ from, cancelUrl, onCancel, - agentConfig, + agentPolicy, packageInfo, children, 'data-test-subj': dataTestSubj, @@ -54,7 +54,7 @@ export const CreatePackageConfigPageLayout: React.FunctionComponent<{

{from === 'edit' ? ( ) : (

@@ -89,7 +89,7 @@ export const CreatePackageConfigPageLayout: React.FunctionComponent<{

@@ -100,18 +100,18 @@ export const CreatePackageConfigPageLayout: React.FunctionComponent<{ const pageDescription = useMemo(() => { return from === 'edit' ? ( - ) : from === 'config' ? ( + ) : from === 'policy' ? ( ) : ( ); }, [from]); @@ -129,7 +129,7 @@ export const CreatePackageConfigPageLayout: React.FunctionComponent<{ data-test-subj={`${dataTestSubj}_cancelBackLink`} > @@ -145,16 +145,16 @@ export const CreatePackageConfigPageLayout: React.FunctionComponent<{ ); const rightColumn = - agentConfig && (from === 'config' || from === 'edit') ? ( + agentPolicy && (from === 'policy' || from === 'edit') ? ( - {agentConfig?.name || '-'} + {agentPolicy?.name || '-'} ) : undefined; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/components/package_config_input_config.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/components/package_policy_input_config.tsx similarity index 83% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/components/package_config_input_config.tsx rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/components/package_policy_input_config.tsx index fd3a64bc760a05..e966ca30c4c973 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/components/package_config_input_config.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/components/package_policy_input_config.tsx @@ -14,29 +14,29 @@ import { EuiSpacer, EuiButtonEmpty, } from '@elastic/eui'; -import { PackageConfigInput, RegistryVarsEntry } from '../../../../types'; +import { PackagePolicyInput, RegistryVarsEntry } from '../../../../types'; import { isAdvancedVar, - PackageConfigConfigValidationResults, + PackagePolicyConfigValidationResults, validationHasErrors, } from '../services'; -import { PackageConfigInputVarField } from './package_config_input_var_field'; +import { PackagePolicyInputVarField } from './package_policy_input_var_field'; const FlexItemWithMaxWidth = styled(EuiFlexItem)` max-width: calc(50% - ${(props) => props.theme.eui.euiSizeL}); `; -export const PackageConfigInputConfig: React.FunctionComponent<{ +export const PackagePolicyInputConfig: React.FunctionComponent<{ packageInputVars?: RegistryVarsEntry[]; - packageConfigInput: PackageConfigInput; - updatePackageConfigInput: (updatedInput: Partial) => void; - inputVarsValidationResults: PackageConfigConfigValidationResults; + packagePolicyInput: PackagePolicyInput; + updatePackagePolicyInput: (updatedInput: Partial) => void; + inputVarsValidationResults: PackagePolicyConfigValidationResults; forceShowErrors?: boolean; }> = memo( ({ packageInputVars, - packageConfigInput, - updatePackageConfigInput, + packagePolicyInput, + updatePackagePolicyInput, inputVarsValidationResults, forceShowErrors, }) => { @@ -76,7 +76,7 @@ export const PackageConfigInputConfig: React.FunctionComponent<{

@@ -85,7 +85,7 @@ export const PackageConfigInputConfig: React.FunctionComponent<{

@@ -97,16 +97,16 @@ export const PackageConfigInputConfig: React.FunctionComponent<{ {requiredVars.map((varDef) => { const { name: varName, type: varType } = varDef; - const value = packageConfigInput.vars![varName].value; + const value = packagePolicyInput.vars![varName].value; return ( - { - updatePackageConfigInput({ + updatePackagePolicyInput({ vars: { - ...packageConfigInput.vars, + ...packagePolicyInput.vars, [varName]: { type: varType, value: newValue, @@ -133,7 +133,7 @@ export const PackageConfigInputConfig: React.FunctionComponent<{ flush="left" > @@ -142,7 +142,7 @@ export const PackageConfigInputConfig: React.FunctionComponent<{ @@ -154,16 +154,16 @@ export const PackageConfigInputConfig: React.FunctionComponent<{ {isShowingAdvanced ? advancedVars.map((varDef) => { const { name: varName, type: varType } = varDef; - const value = packageConfigInput.vars![varName].value; + const value = packagePolicyInput.vars![varName].value; return ( - { - updatePackageConfigInput({ + updatePackagePolicyInput({ vars: { - ...packageConfigInput.vars, + ...packagePolicyInput.vars, [varName]: { type: varType, value: newValue, diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/components/package_config_input_panel.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/components/package_policy_input_panel.tsx similarity index 74% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/components/package_config_input_panel.tsx rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/components/package_policy_input_panel.tsx index 438a17b7ccf356..13504a1ed355a1 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/components/package_config_input_panel.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/components/package_policy_input_panel.tsx @@ -17,18 +17,18 @@ import { EuiSpacer, } from '@elastic/eui'; import { - PackageConfigInput, - PackageConfigInputStream, + PackagePolicyInput, + PackagePolicyInputStream, RegistryInput, RegistryStream, } from '../../../../types'; import { - PackageConfigInputValidationResults, + PackagePolicyInputValidationResults, hasInvalidButRequiredVar, countValidationErrors, } from '../services'; -import { PackageConfigInputConfig } from './package_config_input_config'; -import { PackageConfigInputStreamConfig } from './package_config_input_stream'; +import { PackagePolicyInputConfig } from './package_policy_input_config'; +import { PackagePolicyInputStreamConfig } from './package_policy_input_stream'; const ShortenedHorizontalRule = styled(EuiHorizontalRule)` &&& { @@ -40,18 +40,18 @@ const ShortenedHorizontalRule = styled(EuiHorizontalRule)` const shouldShowStreamsByDefault = ( packageInput: RegistryInput, packageInputStreams: Array, - packageConfigInput: PackageConfigInput + packagePolicyInput: PackagePolicyInput ): boolean => { return ( - packageConfigInput.enabled && - (hasInvalidButRequiredVar(packageInput.vars, packageConfigInput.vars) || + packagePolicyInput.enabled && + (hasInvalidButRequiredVar(packageInput.vars, packagePolicyInput.vars) || Boolean( packageInputStreams.find( (stream) => stream.enabled && hasInvalidButRequiredVar( stream.vars, - packageConfigInput.streams.find( + packagePolicyInput.streams.find( (pkgStream) => stream.data_stream.dataset === pkgStream.data_stream.dataset )?.vars ) @@ -60,25 +60,25 @@ const shouldShowStreamsByDefault = ( ); }; -export const PackageConfigInputPanel: React.FunctionComponent<{ +export const PackagePolicyInputPanel: React.FunctionComponent<{ packageInput: RegistryInput; packageInputStreams: Array; - packageConfigInput: PackageConfigInput; - updatePackageConfigInput: (updatedInput: Partial) => void; - inputValidationResults: PackageConfigInputValidationResults; + packagePolicyInput: PackagePolicyInput; + updatePackagePolicyInput: (updatedInput: Partial) => void; + inputValidationResults: PackagePolicyInputValidationResults; forceShowErrors?: boolean; }> = memo( ({ packageInput, packageInputStreams, - packageConfigInput, - updatePackageConfigInput, + packagePolicyInput, + updatePackagePolicyInput, inputValidationResults, forceShowErrors, }) => { // Showing streams toggle state const [isShowingStreams, setIsShowingStreams] = useState( - shouldShowStreamsByDefault(packageInput, packageInputStreams, packageConfigInput) + shouldShowStreamsByDefault(packageInput, packageInputStreams, packagePolicyInput) ); // Errors state @@ -89,12 +89,12 @@ export const PackageConfigInputPanel: React.FunctionComponent<{ .map((packageInputStream) => { return { packageInputStream, - packageConfigInputStream: packageConfigInput.streams.find( + packagePolicyInputStream: packagePolicyInput.streams.find( (stream) => stream.data_stream.dataset === packageInputStream.data_stream.dataset ), }; }) - .filter((stream) => Boolean(stream.packageConfigInputStream)); + .filter((stream) => Boolean(stream.packagePolicyInputStream)); return ( <> @@ -111,12 +111,12 @@ export const PackageConfigInputPanel: React.FunctionComponent<{ } - checked={packageConfigInput.enabled} + checked={packagePolicyInput.enabled} onChange={(e) => { const enabled = e.target.checked; - updatePackageConfigInput({ + updatePackagePolicyInput({ enabled, - streams: packageConfigInput.streams.map((stream) => ({ + streams: packagePolicyInput.streams.map((stream) => ({ ...stream, enabled, })), @@ -133,7 +133,7 @@ export const PackageConfigInputPanel: React.FunctionComponent<{ @@ -148,7 +148,7 @@ export const PackageConfigInputPanel: React.FunctionComponent<{ aria-label={ isShowingStreams ? i18n.translate( - 'xpack.ingestManager.createPackageConfig.stepConfigure.hideStreamsAriaLabel', + 'xpack.ingestManager.createPackagePolicy.stepConfigure.hideStreamsAriaLabel', { defaultMessage: 'Hide {type} inputs', values: { @@ -157,7 +157,7 @@ export const PackageConfigInputPanel: React.FunctionComponent<{ } ) : i18n.translate( - 'xpack.ingestManager.createPackageConfig.stepConfigure.showStreamsAriaLabel', + 'xpack.ingestManager.createPackagePolicy.stepConfigure.showStreamsAriaLabel', { defaultMessage: 'Show {type} inputs', values: { @@ -175,13 +175,13 @@ export const PackageConfigInputPanel: React.FunctionComponent<{ {/* Header rule break */} {isShowingStreams ? : null} - {/* Input level configuration */} + {/* Input level policy */} {isShowingStreams && packageInput.vars && packageInput.vars.length ? ( - @@ -189,45 +189,45 @@ export const PackageConfigInputPanel: React.FunctionComponent<{ ) : null} - {/* Per-stream configuration */} + {/* Per-stream policy */} {isShowingStreams ? ( - {inputStreams.map(({ packageInputStream, packageConfigInputStream }, index) => ( + {inputStreams.map(({ packageInputStream, packagePolicyInputStream }, index) => ( - + packagePolicyInputStream={packagePolicyInputStream!} + updatePackagePolicyInputStream={( + updatedStream: Partial ) => { - const indexOfUpdatedStream = packageConfigInput.streams.findIndex( + const indexOfUpdatedStream = packagePolicyInput.streams.findIndex( (stream) => stream.data_stream.dataset === packageInputStream.data_stream.dataset ); - const newStreams = [...packageConfigInput.streams]; + const newStreams = [...packagePolicyInput.streams]; newStreams[indexOfUpdatedStream] = { ...newStreams[indexOfUpdatedStream], ...updatedStream, }; - const updatedInput: Partial = { + const updatedInput: Partial = { streams: newStreams, }; // Update input enabled state if needed - if (!packageConfigInput.enabled && updatedStream.enabled) { + if (!packagePolicyInput.enabled && updatedStream.enabled) { updatedInput.enabled = true; } else if ( - packageConfigInput.enabled && + packagePolicyInput.enabled && !newStreams.find((stream) => stream.enabled) ) { updatedInput.enabled = false; } - updatePackageConfigInput(updatedInput); + updatePackagePolicyInput(updatedInput); }} inputStreamValidationResults={ - inputValidationResults.streams![packageConfigInputStream!.id] + inputValidationResults.streams![packagePolicyInputStream!.id] } forceShowErrors={forceShowErrors} /> diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/components/package_config_input_stream.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/components/package_policy_input_stream.tsx similarity index 83% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/components/package_config_input_stream.tsx rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/components/package_policy_input_stream.tsx index 04a0f4e6dbb74b..cbc23f4079d9b2 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/components/package_config_input_stream.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/components/package_policy_input_stream.tsx @@ -16,29 +16,29 @@ import { EuiSpacer, EuiButtonEmpty, } from '@elastic/eui'; -import { PackageConfigInputStream, RegistryStream, RegistryVarsEntry } from '../../../../types'; +import { PackagePolicyInputStream, RegistryStream, RegistryVarsEntry } from '../../../../types'; import { isAdvancedVar, - PackageConfigConfigValidationResults, + PackagePolicyConfigValidationResults, validationHasErrors, } from '../services'; -import { PackageConfigInputVarField } from './package_config_input_var_field'; +import { PackagePolicyInputVarField } from './package_policy_input_var_field'; const FlexItemWithMaxWidth = styled(EuiFlexItem)` max-width: calc(50% - ${(props) => props.theme.eui.euiSizeL}); `; -export const PackageConfigInputStreamConfig: React.FunctionComponent<{ +export const PackagePolicyInputStreamConfig: React.FunctionComponent<{ packageInputStream: RegistryStream; - packageConfigInputStream: PackageConfigInputStream; - updatePackageConfigInputStream: (updatedStream: Partial) => void; - inputStreamValidationResults: PackageConfigConfigValidationResults; + packagePolicyInputStream: PackagePolicyInputStream; + updatePackagePolicyInputStream: (updatedStream: Partial) => void; + inputStreamValidationResults: PackagePolicyConfigValidationResults; forceShowErrors?: boolean; }> = memo( ({ packageInputStream, - packageConfigInputStream, - updatePackageConfigInputStream, + packagePolicyInputStream, + updatePackagePolicyInputStream, inputStreamValidationResults, forceShowErrors, }) => { @@ -77,10 +77,10 @@ export const PackageConfigInputStreamConfig: React.FunctionComponent<{ { const enabled = e.target.checked; - updatePackageConfigInputStream({ + updatePackagePolicyInputStream({ enabled, }); }} @@ -100,16 +100,16 @@ export const PackageConfigInputStreamConfig: React.FunctionComponent<{ {requiredVars.map((varDef) => { const { name: varName, type: varType } = varDef; - const value = packageConfigInputStream.vars![varName].value; + const value = packagePolicyInputStream.vars![varName].value; return ( - { - updatePackageConfigInputStream({ + updatePackagePolicyInputStream({ vars: { - ...packageConfigInputStream.vars, + ...packagePolicyInputStream.vars, [varName]: { type: varType, value: newValue, @@ -135,7 +135,7 @@ export const PackageConfigInputStreamConfig: React.FunctionComponent<{ flush="left" > @@ -144,7 +144,7 @@ export const PackageConfigInputStreamConfig: React.FunctionComponent<{ @@ -156,16 +156,16 @@ export const PackageConfigInputStreamConfig: React.FunctionComponent<{ {isShowingAdvanced ? advancedVars.map((varDef) => { const { name: varName, type: varType } = varDef; - const value = packageConfigInputStream.vars![varName].value; + const value = packagePolicyInputStream.vars![varName].value; return ( - { - updatePackageConfigInputStream({ + updatePackagePolicyInputStream({ vars: { - ...packageConfigInputStream.vars, + ...packagePolicyInputStream.vars, [varName]: { type: varType, value: newValue, diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/components/package_config_input_var_field.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/components/package_policy_input_var_field.tsx similarity index 95% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/components/package_config_input_var_field.tsx rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/components/package_policy_input_var_field.tsx index eb681096a080e6..3620b11948b541 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/components/package_config_input_var_field.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/components/package_policy_input_var_field.tsx @@ -12,7 +12,7 @@ import { RegistryVarsEntry } from '../../../../types'; import 'brace/mode/yaml'; import 'brace/theme/textmate'; -export const PackageConfigInputVarField: React.FunctionComponent<{ +export const PackagePolicyInputVarField: React.FunctionComponent<{ varDef: RegistryVarsEntry; value: any; onChange: (newValue: any) => void; @@ -78,7 +78,7 @@ export const PackageConfigInputVarField: React.FunctionComponent<{ !required ? ( diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/index.tsx similarity index 60% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/index.tsx rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/index.tsx index 74cbcdca512dbb..bdd43b8385ae8a 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/index.tsx @@ -19,32 +19,32 @@ import { } from '@elastic/eui'; import { EuiStepProps } from '@elastic/eui/src/components/steps/step'; import { - AgentConfig, + AgentPolicy, PackageInfo, - NewPackageConfig, - CreatePackageConfigRouteState, + NewPackagePolicy, + CreatePackagePolicyRouteState, } from '../../../types'; import { useLink, useBreadcrumbs, - sendCreatePackageConfig, + sendCreatePackagePolicy, useCore, useConfig, sendGetAgentStatus, } from '../../../hooks'; import { Loading } from '../../../components'; -import { ConfirmDeployConfigModal } from '../components'; -import { CreatePackageConfigPageLayout } from './components'; -import { CreatePackageConfigFrom, PackageConfigFormState } from './types'; +import { ConfirmDeployAgentPolicyModal } from '../components'; +import { CreatePackagePolicyPageLayout } from './components'; +import { CreatePackagePolicyFrom, PackagePolicyFormState } from './types'; import { - PackageConfigValidationResults, - validatePackageConfig, + PackagePolicyValidationResults, + validatePackagePolicy, validationHasErrors, } from './services'; import { StepSelectPackage } from './step_select_package'; -import { StepSelectConfig } from './step_select_config'; -import { StepConfigurePackage } from './step_configure_package'; -import { StepDefinePackageConfig } from './step_define_package_config'; +import { StepSelectAgentPolicy } from './step_select_agent_policy'; +import { StepConfigurePackagePolicy } from './step_configure_package'; +import { StepDefinePackagePolicy } from './step_define_package_policy'; import { useIntraAppState } from '../../../hooks/use_intra_app_state'; const StepsWithLessPadding = styled(EuiSteps)` @@ -53,7 +53,7 @@ const StepsWithLessPadding = styled(EuiSteps)` } `; -export const CreatePackageConfigPage: React.FunctionComponent = () => { +export const CreatePackagePolicyPage: React.FunctionComponent = () => { const { notifications, chrome: { getIsNavDrawerLocked$ }, @@ -64,12 +64,12 @@ export const CreatePackageConfigPage: React.FunctionComponent = () => { fleet: { enabled: isFleetEnabled }, } = useConfig(); const { - params: { configId, pkgkey }, + params: { policyId, pkgkey }, } = useRouteMatch(); const { getHref, getPath } = useLink(); const history = useHistory(); - const routeState = useIntraAppState(); - const from: CreatePackageConfigFrom = configId ? 'config' : 'package'; + const routeState = useIntraAppState(); + const from: CreatePackagePolicyFrom = policyId ? 'policy' : 'package'; const [isNavDrawerLocked, setIsNavDrawerLocked] = useState(false); useEffect(() => { @@ -80,52 +80,52 @@ export const CreatePackageConfigPage: React.FunctionComponent = () => { return () => subscription.unsubscribe(); }); - // Agent config and package info states - const [agentConfig, setAgentConfig] = useState(); + // Agent policy and package info states + const [agentPolicy, setAgentPolicy] = useState(); const [packageInfo, setPackageInfo] = useState(); const [isLoadingSecondStep, setIsLoadingSecondStep] = useState(false); - const agentConfigId = agentConfig?.id; + const agentPolicyId = agentPolicy?.id; // Retrieve agent count useEffect(() => { const getAgentCount = async () => { - if (agentConfigId) { - const { data } = await sendGetAgentStatus({ configId: agentConfigId }); + if (agentPolicyId) { + const { data } = await sendGetAgentStatus({ policyId: agentPolicyId }); if (data?.results.total) { setAgentCount(data.results.total); } } }; - if (isFleetEnabled && agentConfigId) { + if (isFleetEnabled && agentPolicyId) { getAgentCount(); } - }, [agentConfigId, isFleetEnabled]); + }, [agentPolicyId, isFleetEnabled]); const [agentCount, setAgentCount] = useState(0); - // New package config state - const [packageConfig, setPackageConfig] = useState({ + // New package policy state + const [packagePolicy, setPackagePolicy] = useState({ name: '', description: '', namespace: '', - config_id: '', + policy_id: '', enabled: true, output_id: '', // TODO: Blank for now as we only support default output inputs: [], }); - // Package config validation state - const [validationResults, setValidationResults] = useState(); + // Package policy validation state + const [validationResults, setValidationResults] = useState(); // Form state - const [formState, setFormState] = useState('INVALID'); + const [formState, setFormState] = useState('INVALID'); // Update package info method const updatePackageInfo = useCallback( (updatedPackageInfo: PackageInfo | undefined) => { if (updatedPackageInfo) { setPackageInfo(updatedPackageInfo); - if (agentConfig) { + if (agentPolicy) { setFormState('VALID'); } } else { @@ -136,70 +136,70 @@ export const CreatePackageConfigPage: React.FunctionComponent = () => { // eslint-disable-next-line no-console console.debug('Package info updated', updatedPackageInfo); }, - [agentConfig, setPackageInfo, setFormState] + [agentPolicy, setPackageInfo, setFormState] ); - // Update agent config method - const updateAgentConfig = useCallback( - (updatedAgentConfig: AgentConfig | undefined) => { - if (updatedAgentConfig) { - setAgentConfig(updatedAgentConfig); + // Update agent policy method + const updateAgentPolicy = useCallback( + (updatedAgentPolicy: AgentPolicy | undefined) => { + if (updatedAgentPolicy) { + setAgentPolicy(updatedAgentPolicy); if (packageInfo) { setFormState('VALID'); } } else { setFormState('INVALID'); - setAgentConfig(undefined); + setAgentPolicy(undefined); } // eslint-disable-next-line no-console - console.debug('Agent config updated', updatedAgentConfig); + console.debug('Agent policy updated', updatedAgentPolicy); }, - [packageInfo, setAgentConfig, setFormState] + [packageInfo, setAgentPolicy, setFormState] ); const hasErrors = validationResults ? validationHasErrors(validationResults) : false; - // Update package config validation - const updatePackageConfigValidation = useCallback( - (newPackageConfig?: NewPackageConfig) => { + // Update package policy validation + const updatePackagePolicyValidation = useCallback( + (newPackagePolicy?: NewPackagePolicy) => { if (packageInfo) { - const newValidationResult = validatePackageConfig( - newPackageConfig || packageConfig, + const newValidationResult = validatePackagePolicy( + newPackagePolicy || packagePolicy, packageInfo ); setValidationResults(newValidationResult); // eslint-disable-next-line no-console - console.debug('Package config validation results', newValidationResult); + console.debug('Package policy validation results', newValidationResult); return newValidationResult; } }, - [packageConfig, packageInfo] + [packagePolicy, packageInfo] ); - // Update package config method - const updatePackageConfig = useCallback( - (updatedFields: Partial) => { - const newPackageConfig = { - ...packageConfig, + // Update package policy method + const updatePackagePolicy = useCallback( + (updatedFields: Partial) => { + const newPackagePolicy = { + ...packagePolicy, ...updatedFields, }; - setPackageConfig(newPackageConfig); + setPackagePolicy(newPackagePolicy); // eslint-disable-next-line no-console - console.debug('Package config updated', newPackageConfig); - const newValidationResults = updatePackageConfigValidation(newPackageConfig); - const hasPackage = newPackageConfig.package; + console.debug('Package policy updated', newPackagePolicy); + const newValidationResults = updatePackagePolicyValidation(newPackagePolicy); + const hasPackage = newPackagePolicy.package; const hasValidationErrors = newValidationResults ? validationHasErrors(newValidationResults) : false; - const hasAgentConfig = newPackageConfig.config_id && newPackageConfig.config_id !== ''; - if (hasPackage && hasAgentConfig && !hasValidationErrors) { + const hasAgentPolicy = newPackagePolicy.policy_id && newPackagePolicy.policy_id !== ''; + if (hasPackage && hasAgentPolicy && !hasValidationErrors) { setFormState('VALID'); } }, - [packageConfig, updatePackageConfigValidation] + [packagePolicy, updatePackagePolicyValidation] ); // Cancel path @@ -207,10 +207,10 @@ export const CreatePackageConfigPage: React.FunctionComponent = () => { if (routeState && routeState.onCancelUrl) { return routeState.onCancelUrl; } - return from === 'config' - ? getHref('configuration_details', { configId: agentConfigId || configId }) + return from === 'policy' + ? getHref('policy_details', { policyId: agentPolicyId || policyId }) : getHref('integration_details', { pkgkey }); - }, [agentConfigId, configId, from, getHref, pkgkey, routeState]); + }, [agentPolicyId, policyId, from, getHref, pkgkey, routeState]); const cancelClickHandler: ReactEventHandler = useCallback( (ev) => { @@ -222,10 +222,10 @@ export const CreatePackageConfigPage: React.FunctionComponent = () => { [routeState, navigateToApp] ); - // Save package config - const savePackageConfig = async () => { + // Save package policy + const savePackagePolicy = async () => { setFormState('LOADING'); - const result = await sendCreatePackageConfig(packageConfig); + const result = await sendCreatePackagePolicy(packagePolicy); setFormState('SUBMITTED'); return result; }; @@ -239,7 +239,7 @@ export const CreatePackageConfigPage: React.FunctionComponent = () => { setFormState('CONFIRM'); return; } - const { error, data } = await savePackageConfig(); + const { error, data } = await savePackagePolicy(); if (!error) { if (routeState && routeState.onSaveNavigateTo) { navigateToApp( @@ -248,26 +248,26 @@ export const CreatePackageConfigPage: React.FunctionComponent = () => { : routeState.onSaveNavigateTo) ); } else { - history.push(getPath('configuration_details', { configId: agentConfig?.id || configId })); + history.push(getPath('policy_details', { policyId: agentPolicy?.id || policyId })); } notifications.toasts.addSuccess({ - title: i18n.translate('xpack.ingestManager.createPackageConfig.addedNotificationTitle', { - defaultMessage: `Successfully added '{packageConfigName}'`, + title: i18n.translate('xpack.ingestManager.createPackagePolicy.addedNotificationTitle', { + defaultMessage: `Successfully added '{packagePolicyName}'`, values: { - packageConfigName: packageConfig.name, + packagePolicyName: packagePolicy.name, }, }), text: - agentCount && agentConfig - ? i18n.translate('xpack.ingestManager.createPackageConfig.addedNotificationMessage', { - defaultMessage: `Fleet will deploy updates to all agents that use the '{agentConfigName}' configuration`, + agentCount && agentPolicy + ? i18n.translate('xpack.ingestManager.createPackagePolicy.addedNotificationMessage', { + defaultMessage: `Fleet will deploy updates to all agents that use the '{agentPolicyName}' policy`, values: { - agentConfigName: agentConfig.name, + agentPolicyName: agentPolicy.name, }, }) : undefined, - 'data-test-subj': 'packageConfigCreateSuccessToast', + 'data-test-subj': 'packagePolicyCreateSuccessToast', }); } else { notifications.toasts.addError(error, { @@ -281,53 +281,53 @@ export const CreatePackageConfigPage: React.FunctionComponent = () => { from, cancelUrl, onCancel: cancelClickHandler, - agentConfig, + agentPolicy, packageInfo, }; - const stepSelectConfig = useMemo( + const stepSelectAgentPolicy = useMemo( () => ( - ), - [pkgkey, updatePackageInfo, agentConfig, updateAgentConfig] + [pkgkey, updatePackageInfo, agentPolicy, updateAgentPolicy] ); const stepSelectPackage = useMemo( () => ( ), - [configId, updateAgentConfig, packageInfo, updatePackageInfo] + [policyId, updateAgentPolicy, packageInfo, updatePackageInfo] ); - const stepConfigurePackage = useMemo( + const stepConfigurePackagePolicy = useMemo( () => isLoadingSecondStep ? ( - ) : agentConfig && packageInfo ? ( + ) : agentPolicy && packageInfo ? ( <> - - @@ -336,12 +336,12 @@ export const CreatePackageConfigPage: React.FunctionComponent = () => {
), [ - agentConfig, + agentPolicy, formState, isLoadingSecondStep, - packageConfig, + packagePolicy, packageInfo, - updatePackageConfig, + updatePackagePolicy, validationResults, ] ); @@ -350,38 +350,38 @@ export const CreatePackageConfigPage: React.FunctionComponent = () => { from === 'package' ? { title: i18n.translate( - 'xpack.ingestManager.createPackageConfig.stepSelectAgentConfigTitle', + 'xpack.ingestManager.createPackagePolicy.stepSelectAgentPolicyTitle', { - defaultMessage: 'Select an agent configuration', + defaultMessage: 'Select an agent policy', } ), - children: stepSelectConfig, + children: stepSelectAgentPolicy, } : { - title: i18n.translate('xpack.ingestManager.createPackageConfig.stepSelectPackageTitle', { + title: i18n.translate('xpack.ingestManager.createPackagePolicy.stepSelectPackageTitle', { defaultMessage: 'Select an integration', }), children: stepSelectPackage, }, { title: i18n.translate( - 'xpack.ingestManager.createPackageConfig.stepConfigurePackageConfigTitle', + 'xpack.ingestManager.createPackagePolicy.stepConfigurePackagePolicyTitle', { defaultMessage: 'Configure integration', } ), - status: !packageInfo || !agentConfig || isLoadingSecondStep ? 'disabled' : undefined, + status: !packageInfo || !agentPolicy || isLoadingSecondStep ? 'disabled' : undefined, 'data-test-subj': 'dataCollectionSetupStep', - children: stepConfigurePackage, + children: stepConfigurePackagePolicy, }, ]; return ( - - {formState === 'CONFIRM' && agentConfig && ( - + {formState === 'CONFIRM' && agentPolicy && ( + setFormState('VALID')} /> @@ -393,8 +393,8 @@ export const CreatePackageConfigPage: React.FunctionComponent = () => { pkgkey={`${packageInfo.name}-${packageInfo.version}`} /> ) - : agentConfig && ( - + : agentPolicy && ( + )} @@ -410,10 +410,10 @@ export const CreatePackageConfigPage: React.FunctionComponent = () => { > - {!isLoadingSecondStep && agentConfig && packageInfo && formState === 'INVALID' ? ( + {!isLoadingSecondStep && agentPolicy && packageInfo && formState === 'INVALID' ? ( ) : null} @@ -425,10 +425,10 @@ export const CreatePackageConfigPage: React.FunctionComponent = () => { color="ghost" href={cancelUrl} onClick={cancelClickHandler} - data-test-subj="createPackageConfigCancelButton" + data-test-subj="createPackagePolicyCancelButton" > @@ -441,10 +441,10 @@ export const CreatePackageConfigPage: React.FunctionComponent = () => { iconType="save" color="primary" fill - data-test-subj="createPackageConfigSaveButton" + data-test-subj="createPackagePolicySaveButton" > @@ -453,15 +453,15 @@ export const CreatePackageConfigPage: React.FunctionComponent = () => { - + ); }; -const ConfigurationBreadcrumb: React.FunctionComponent<{ - configName: string; - configId: string; -}> = ({ configName, configId }) => { - useBreadcrumbs('add_integration_from_configuration', { configName, configId }); +const PolicyBreadcrumb: React.FunctionComponent<{ + policyName: string; + policyId: string; +}> = ({ policyName, policyId }) => { + useBreadcrumbs('add_integration_from_policy', { policyName, policyId }); return null; }; @@ -469,6 +469,6 @@ const IntegrationBreadcrumb: React.FunctionComponent<{ pkgTitle: string; pkgkey: string; }> = ({ pkgTitle, pkgkey }) => { - useBreadcrumbs('add_integration_to_configuration', { pkgTitle, pkgkey }); + useBreadcrumbs('add_integration_to_policy', { pkgTitle, pkgkey }); return null; }; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/services/has_invalid_but_required_var.test.ts b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/services/has_invalid_but_required_var.test.ts similarity index 100% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/services/has_invalid_but_required_var.test.ts rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/services/has_invalid_but_required_var.test.ts diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/services/has_invalid_but_required_var.ts b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/services/has_invalid_but_required_var.ts similarity index 60% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/services/has_invalid_but_required_var.ts rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/services/has_invalid_but_required_var.ts index f632d40a05621c..142625f3eb2a9b 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/services/has_invalid_but_required_var.ts +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/services/has_invalid_but_required_var.ts @@ -3,23 +3,23 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { PackageConfigConfigRecord, RegistryVarsEntry } from '../../../../types'; -import { validatePackageConfigConfig } from './'; +import { PackagePolicyConfigRecord, RegistryVarsEntry } from '../../../../types'; +import { validatePackagePolicyConfig } from './'; export const hasInvalidButRequiredVar = ( registryVars?: RegistryVarsEntry[], - packageConfigVars?: PackageConfigConfigRecord + packagePolicyVars?: PackagePolicyConfigRecord ): boolean => { return ( - (registryVars && !packageConfigVars) || + (registryVars && !packagePolicyVars) || Boolean( registryVars && registryVars.find( (registryVar) => registryVar.required && - (!packageConfigVars || - !packageConfigVars[registryVar.name] || - validatePackageConfigConfig(packageConfigVars[registryVar.name], registryVar)?.length) + (!packagePolicyVars || + !packagePolicyVars[registryVar.name] || + validatePackagePolicyConfig(packagePolicyVars[registryVar.name], registryVar)?.length) ) ) ); diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/services/index.ts b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/services/index.ts similarity index 67% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/services/index.ts rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/services/index.ts index 0d33a4e113f033..6d8fd4c35c0fab 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/services/index.ts +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/services/index.ts @@ -6,11 +6,11 @@ export { isAdvancedVar } from './is_advanced_var'; export { hasInvalidButRequiredVar } from './has_invalid_but_required_var'; export { - PackageConfigValidationResults, - PackageConfigConfigValidationResults, - PackageConfigInputValidationResults, - validatePackageConfig, - validatePackageConfigConfig, + PackagePolicyValidationResults, + PackagePolicyConfigValidationResults, + PackagePolicyInputValidationResults, + validatePackagePolicy, + validatePackagePolicyConfig, validationHasErrors, countValidationErrors, -} from './validate_package_config'; +} from './validate_package_policy'; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/services/is_advanced_var.test.ts b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/services/is_advanced_var.test.ts similarity index 100% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/services/is_advanced_var.test.ts rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/services/is_advanced_var.test.ts diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/services/is_advanced_var.ts b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/services/is_advanced_var.ts similarity index 100% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/services/is_advanced_var.ts rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/services/is_advanced_var.ts diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/services/validate_package_config.ts.test.ts b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/services/validate_package_policy.test..ts similarity index 91% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/services/validate_package_config.ts.test.ts rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/services/validate_package_policy.test..ts index 47874525b8a5a2..aae750cb674991 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/services/validate_package_config.ts.test.ts +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/services/validate_package_policy.test..ts @@ -6,12 +6,12 @@ import { PackageInfo, InstallationStatus, - NewPackageConfig, + NewPackagePolicy, RegistryConfigTemplate, } from '../../../../types'; -import { validatePackageConfig, validationHasErrors } from './validate_package_config'; +import { validatePackagePolicy, validationHasErrors } from './validate_package_policy'; -describe('Ingest Manager - validatePackageConfig()', () => { +describe('Ingest Manager - validatePackagePolicy()', () => { const mockPackage = ({ name: 'mock-package', title: 'Mock package', @@ -92,9 +92,9 @@ describe('Ingest Manager - validatePackageConfig()', () => { ], config_templates: [ { - name: 'pkgConfig1', - title: 'Package config 1', - description: 'test package config', + name: 'pkgPolicy1', + title: 'Package policy 1', + description: 'test package policy', inputs: [ { type: 'foo', @@ -141,10 +141,10 @@ describe('Ingest Manager - validatePackageConfig()', () => { ], } as unknown) as PackageInfo; - const validPackageConfig: NewPackageConfig = { - name: 'pkgConfig1-1', + const validPackagePolicy: NewPackagePolicy = { + name: 'pkgPolicy1-1', namespace: 'default', - config_id: 'test-config', + policy_id: 'test-policy', enabled: true, output_id: 'test-output', inputs: [ @@ -226,8 +226,8 @@ describe('Ingest Manager - validatePackageConfig()', () => { ], }; - const invalidPackageConfig: NewPackageConfig = { - ...validPackageConfig, + const invalidPackagePolicy: NewPackagePolicy = { + ...validPackagePolicy, name: '', inputs: [ { @@ -350,14 +350,14 @@ describe('Ingest Manager - validatePackageConfig()', () => { }, }; - it('returns no errors for valid package config', () => { - expect(validatePackageConfig(validPackageConfig, mockPackage)).toEqual( + it('returns no errors for valid package policy', () => { + expect(validatePackagePolicy(validPackagePolicy, mockPackage)).toEqual( noErrorsValidationResults ); }); - it('returns errors for invalid package config', () => { - expect(validatePackageConfig(invalidPackageConfig, mockPackage)).toEqual({ + it('returns errors for invalid package policy', () => { + expect(validatePackagePolicy(invalidPackagePolicy, mockPackage)).toEqual({ name: ['Name is required'], description: null, namespace: null, @@ -397,17 +397,17 @@ describe('Ingest Manager - validatePackageConfig()', () => { }); it('returns no errors for disabled inputs', () => { - const disabledInputs = invalidPackageConfig.inputs.map((input) => ({ + const disabledInputs = invalidPackagePolicy.inputs.map((input) => ({ ...input, enabled: false, })); expect( - validatePackageConfig({ ...validPackageConfig, inputs: disabledInputs }, mockPackage) + validatePackagePolicy({ ...validPackagePolicy, inputs: disabledInputs }, mockPackage) ).toEqual(noErrorsValidationResults); }); - it('returns only package config and input-level errors for disabled streams', () => { - const inputsWithDisabledStreams = invalidPackageConfig.inputs.map((input) => + it('returns only package policy and input-level errors for disabled streams', () => { + const inputsWithDisabledStreams = invalidPackagePolicy.inputs.map((input) => input.streams ? { ...input, @@ -416,8 +416,8 @@ describe('Ingest Manager - validatePackageConfig()', () => { : input ); expect( - validatePackageConfig( - { ...invalidPackageConfig, inputs: inputsWithDisabledStreams }, + validatePackagePolicy( + { ...invalidPackagePolicy, inputs: inputsWithDisabledStreams }, mockPackage ) ).toEqual({ @@ -461,9 +461,9 @@ describe('Ingest Manager - validatePackageConfig()', () => { }); }); - it('returns no errors for packages with no package configs', () => { + it('returns no errors for packages with no package policies', () => { expect( - validatePackageConfig(validPackageConfig, { + validatePackagePolicy(validPackagePolicy, { ...mockPackage, config_templates: undefined, }) @@ -474,7 +474,7 @@ describe('Ingest Manager - validatePackageConfig()', () => { inputs: null, }); expect( - validatePackageConfig(validPackageConfig, { + validatePackagePolicy(validPackagePolicy, { ...mockPackage, config_templates: [], }) @@ -488,7 +488,7 @@ describe('Ingest Manager - validatePackageConfig()', () => { it('returns no errors for packages with no inputs', () => { expect( - validatePackageConfig(validPackageConfig, { + validatePackagePolicy(validPackagePolicy, { ...mockPackage, config_templates: [{} as RegistryConfigTemplate], }) @@ -499,7 +499,7 @@ describe('Ingest Manager - validatePackageConfig()', () => { inputs: null, }); expect( - validatePackageConfig(validPackageConfig, { + validatePackagePolicy(validPackagePolicy, { ...mockPackage, config_templates: [({ inputs: [] } as unknown) as RegistryConfigTemplate], }) @@ -553,7 +553,7 @@ describe('Ingest Manager - validationHasErrors()', () => { ).toBe(false); }); - it('returns true for package config validation results with errors', () => { + it('returns true for package policy validation results with errors', () => { expect( validationHasErrors({ name: ['name error'], @@ -595,7 +595,7 @@ describe('Ingest Manager - validationHasErrors()', () => { ).toBe(true); }); - it('returns false for package config validation results with no errors', () => { + it('returns false for package policy validation results with no errors', () => { expect( validationHasErrors({ name: null, diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/services/validate_package_config.ts b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/services/validate_package_policy.ts similarity index 76% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/services/validate_package_config.ts rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/services/validate_package_policy.ts index 0514ad574a8cdb..f375352c5a0557 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/services/validate_package_config.ts +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/services/validate_package_policy.ts @@ -7,10 +7,10 @@ import { i18n } from '@kbn/i18n'; import { safeLoad } from 'js-yaml'; import { getFlattenedObject } from '../../../../services'; import { - NewPackageConfig, - PackageConfigInput, - PackageConfigInputStream, - PackageConfigConfigRecordEntry, + NewPackagePolicy, + PackagePolicyInput, + PackagePolicyInputStream, + PackagePolicyConfigRecordEntry, PackageInfo, RegistryInput, RegistryStream, @@ -21,47 +21,47 @@ type Errors = string[] | null; type ValidationEntry = Record; -export interface PackageConfigConfigValidationResults { +export interface PackagePolicyConfigValidationResults { vars?: ValidationEntry; } -export type PackageConfigInputValidationResults = PackageConfigConfigValidationResults & { - streams?: Record; +export type PackagePolicyInputValidationResults = PackagePolicyConfigValidationResults & { + streams?: Record; }; -export interface PackageConfigValidationResults { +export interface PackagePolicyValidationResults { name: Errors; description: Errors; namespace: Errors; - inputs: Record | null; + inputs: Record | null; } /* - * Returns validation information for a given package config and package info - * Note: this method assumes that `packageConfig` is correctly structured for the given package + * Returns validation information for a given package policy and package info + * Note: this method assumes that `packagePolicy` is correctly structured for the given package */ -export const validatePackageConfig = ( - packageConfig: NewPackageConfig, +export const validatePackagePolicy = ( + packagePolicy: NewPackagePolicy, packageInfo: PackageInfo -): PackageConfigValidationResults => { - const validationResults: PackageConfigValidationResults = { +): PackagePolicyValidationResults => { + const validationResults: PackagePolicyValidationResults = { name: null, description: null, namespace: null, inputs: {}, }; - if (!packageConfig.name.trim()) { + if (!packagePolicy.name.trim()) { validationResults.name = [ - i18n.translate('xpack.ingestManager.packageConfigValidation.nameRequiredErrorMessage', { + i18n.translate('xpack.ingestManager.packagePolicyValidation.nameRequiredErrorMessage', { defaultMessage: 'Name is required', }), ]; } - if (!packageConfig.namespace.trim()) { + if (!packagePolicy.namespace.trim()) { validationResults.namespace = [ - i18n.translate('xpack.ingestManager.packageConfigValidation.namespaceRequiredErrorMessage', { + i18n.translate('xpack.ingestManager.packagePolicyValidation.namespaceRequiredErrorMessage', { defaultMessage: 'Namespace is required', }), ]; @@ -93,13 +93,13 @@ export const validatePackageConfig = ( return datasets; }, {} as Record); - // Validate each package config input with either its own config fields or streams - packageConfig.inputs.forEach((input) => { + // Validate each package policy input with either its own config fields or streams + packagePolicy.inputs.forEach((input) => { if (!input.vars && !input.streams) { return; } - const inputValidationResults: PackageConfigInputValidationResults = { + const inputValidationResults: PackagePolicyInputValidationResults = { vars: undefined, streams: {}, }; @@ -117,7 +117,7 @@ export const validatePackageConfig = ( if (inputConfigs.length) { inputValidationResults.vars = inputConfigs.reduce((results, [name, configEntry]) => { results[name] = input.enabled - ? validatePackageConfigConfig(configEntry, inputVarsByName[name]) + ? validatePackagePolicyConfig(configEntry, inputVarsByName[name]) : null; return results; }, {} as ValidationEntry); @@ -128,7 +128,7 @@ export const validatePackageConfig = ( // Validate each input stream with config fields if (input.streams.length) { input.streams.forEach((stream) => { - const streamValidationResults: PackageConfigConfigValidationResults = {}; + const streamValidationResults: PackagePolicyConfigValidationResults = {}; // Validate stream-level config fields if (stream.vars) { @@ -146,7 +146,7 @@ export const validatePackageConfig = ( (results, [name, configEntry]) => { results[name] = input.enabled && stream.enabled - ? validatePackageConfigConfig(configEntry, streamVarsByName[name]) + ? validatePackagePolicyConfig(configEntry, streamVarsByName[name]) : null; return results; }, @@ -171,8 +171,8 @@ export const validatePackageConfig = ( return validationResults; }; -export const validatePackageConfigConfig = ( - configEntry: PackageConfigConfigRecordEntry, +export const validatePackagePolicyConfig = ( + configEntry: PackagePolicyConfigRecordEntry, varDef: RegistryVarsEntry ): string[] | null => { const errors = []; @@ -186,7 +186,7 @@ export const validatePackageConfigConfig = ( if (varDef.required) { if (parsedValue === undefined || (typeof parsedValue === 'string' && !parsedValue)) { errors.push( - i18n.translate('xpack.ingestManager.packageConfigValidation.requiredErrorMessage', { + i18n.translate('xpack.ingestManager.packagePolicyValidation.requiredErrorMessage', { defaultMessage: '{fieldName} is required', values: { fieldName: varDef.title || varDef.name, @@ -202,7 +202,7 @@ export const validatePackageConfigConfig = ( } catch (e) { errors.push( i18n.translate( - 'xpack.ingestManager.packageConfigValidation.invalidYamlFormatErrorMessage', + 'xpack.ingestManager.packagePolicyValidation.invalidYamlFormatErrorMessage', { defaultMessage: 'Invalid YAML format', } @@ -214,7 +214,7 @@ export const validatePackageConfigConfig = ( if (varDef.multi) { if (parsedValue && !Array.isArray(parsedValue)) { errors.push( - i18n.translate('xpack.ingestManager.packageConfigValidation.invalidArrayErrorMessage', { + i18n.translate('xpack.ingestManager.packagePolicyValidation.invalidArrayErrorMessage', { defaultMessage: 'Invalid format', }) ); @@ -224,7 +224,7 @@ export const validatePackageConfigConfig = ( (!parsedValue || (Array.isArray(parsedValue) && parsedValue.length === 0)) ) { errors.push( - i18n.translate('xpack.ingestManager.packageConfigValidation.requiredErrorMessage', { + i18n.translate('xpack.ingestManager.packagePolicyValidation.requiredErrorMessage', { defaultMessage: '{fieldName} is required', values: { fieldName: varDef.title || varDef.name, @@ -239,9 +239,9 @@ export const validatePackageConfigConfig = ( export const countValidationErrors = ( validationResults: - | PackageConfigValidationResults - | PackageConfigInputValidationResults - | PackageConfigConfigValidationResults + | PackagePolicyValidationResults + | PackagePolicyInputValidationResults + | PackagePolicyConfigValidationResults ): number => { const flattenedValidation = getFlattenedObject(validationResults); const errors = Object.values(flattenedValidation).filter((value) => Boolean(value)) || []; @@ -250,9 +250,9 @@ export const countValidationErrors = ( export const validationHasErrors = ( validationResults: - | PackageConfigValidationResults - | PackageConfigInputValidationResults - | PackageConfigConfigValidationResults + | PackagePolicyValidationResults + | PackagePolicyInputValidationResults + | PackagePolicyConfigValidationResults ): boolean => { return countValidationErrors(validationResults) > 0; }; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/step_configure_package.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/step_configure_package.tsx similarity index 68% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/step_configure_package.tsx rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/step_configure_package.tsx index a41d4d72db34ca..b77153daee2fc5 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/step_configure_package.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/step_configure_package.tsx @@ -5,11 +5,11 @@ */ import React from 'react'; import { EuiHorizontalRule, EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; -import { PackageInfo, RegistryStream, NewPackageConfig, PackageConfigInput } from '../../../types'; +import { PackageInfo, RegistryStream, NewPackagePolicy, PackagePolicyInput } from '../../../types'; import { Loading } from '../../../components'; -import { PackageConfigValidationResults } from './services'; -import { PackageConfigInputPanel, CustomPackageConfig } from './components'; -import { CreatePackageConfigFrom } from './types'; +import { PackagePolicyValidationResults } from './services'; +import { PackagePolicyInputPanel, CustomPackagePolicy } from './components'; +import { CreatePackagePolicyFrom } from './types'; const findStreamsForInputType = ( inputType: string, @@ -33,20 +33,20 @@ const findStreamsForInputType = ( return streams; }; -export const StepConfigurePackage: React.FunctionComponent<{ - from?: CreatePackageConfigFrom; +export const StepConfigurePackagePolicy: React.FunctionComponent<{ + from?: CreatePackagePolicyFrom; packageInfo: PackageInfo; - packageConfig: NewPackageConfig; - packageConfigId?: string; - updatePackageConfig: (fields: Partial) => void; - validationResults: PackageConfigValidationResults; + packagePolicy: NewPackagePolicy; + packagePolicyId?: string; + updatePackagePolicy: (fields: Partial) => void; + validationResults: PackagePolicyValidationResults; submitAttempted: boolean; }> = ({ - from = 'config', + from = 'policy', packageInfo, - packageConfig, - packageConfigId, - updatePackageConfig, + packagePolicy, + packagePolicyId, + updatePackagePolicy, validationResults, submitAttempted, }) => { @@ -61,30 +61,30 @@ export const StepConfigurePackage: React.FunctionComponent<{ {packageInfo.config_templates[0].inputs.map((packageInput) => { - const packageConfigInput = packageConfig.inputs.find( + const packagePolicyInput = packagePolicy.inputs.find( (input) => input.type === packageInput.type ); const packageInputStreams = findStreamsForInputType(packageInput.type, packageInfo); - return packageConfigInput ? ( + return packagePolicyInput ? ( - ) => { - const indexOfUpdatedInput = packageConfig.inputs.findIndex( + packagePolicyInput={packagePolicyInput} + updatePackagePolicyInput={(updatedInput: Partial) => { + const indexOfUpdatedInput = packagePolicy.inputs.findIndex( (input) => input.type === packageInput.type ); - const newInputs = [...packageConfig.inputs]; + const newInputs = [...packagePolicy.inputs]; newInputs[indexOfUpdatedInput] = { ...newInputs[indexOfUpdatedInput], ...updatedInput, }; - updatePackageConfig({ + updatePackagePolicy({ inputs: newInputs, }); }} - inputValidationResults={validationResults!.inputs![packageConfigInput.type]} + inputValidationResults={validationResults!.inputs![packagePolicyInput.type]} forceShowErrors={submitAttempted} /> @@ -94,11 +94,11 @@ export const StepConfigurePackage: React.FunctionComponent<{ ) : ( - ); diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/step_define_package_config.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/step_define_package_policy.tsx similarity index 64% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/step_define_package_config.tsx rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/step_define_package_policy.tsx index f487b4e5235e71..86f69208e06382 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/step_define_package_config.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/step_define_package_policy.tsx @@ -16,45 +16,45 @@ import { EuiFlexGroup, EuiFlexItem, } from '@elastic/eui'; -import { AgentConfig, PackageInfo, PackageConfig, NewPackageConfig } from '../../../types'; -import { packageToPackageConfigInputs } from '../../../services'; +import { AgentPolicy, PackageInfo, PackagePolicy, NewPackagePolicy } from '../../../types'; +import { packageToPackagePolicyInputs } from '../../../services'; import { Loading } from '../../../components'; -import { PackageConfigValidationResults } from './services'; +import { PackagePolicyValidationResults } from './services'; -export const StepDefinePackageConfig: React.FunctionComponent<{ - agentConfig: AgentConfig; +export const StepDefinePackagePolicy: React.FunctionComponent<{ + agentPolicy: AgentPolicy; packageInfo: PackageInfo; - packageConfig: NewPackageConfig; - updatePackageConfig: (fields: Partial) => void; - validationResults: PackageConfigValidationResults; -}> = ({ agentConfig, packageInfo, packageConfig, updatePackageConfig, validationResults }) => { + packagePolicy: NewPackagePolicy; + updatePackagePolicy: (fields: Partial) => void; + validationResults: PackagePolicyValidationResults; +}> = ({ agentPolicy, packageInfo, packagePolicy, updatePackagePolicy, validationResults }) => { // Form show/hide states const [isShowingAdvanced, setIsShowingAdvanced] = useState(false); - // Update package config's package and config info + // Update package policy's package and agent policy info useEffect(() => { - const pkg = packageConfig.package; + const pkg = packagePolicy.package; const currentPkgKey = pkg ? `${pkg.name}-${pkg.version}` : ''; const pkgKey = `${packageInfo.name}-${packageInfo.version}`; - // If package has changed, create shell package config with input&stream values based on package info + // If package has changed, create shell package policy with input&stream values based on package info if (currentPkgKey !== pkgKey) { - // Existing package configs on the agent config using the package name, retrieve highest number appended to package config name - const dsPackageNamePattern = new RegExp(`${packageInfo.name}-(\\d+)`); - const dsWithMatchingNames = (agentConfig.package_configs as PackageConfig[]) - .filter((ds) => Boolean(ds.name.match(dsPackageNamePattern))) - .map((ds) => parseInt(ds.name.match(dsPackageNamePattern)![1], 10)) + // Existing package policies on the agent policy using the package name, retrieve highest number appended to package policy name + const pkgPoliciesNamePattern = new RegExp(`${packageInfo.name}-(\\d+)`); + const pkgPoliciesWithMatchingNames = (agentPolicy.package_policies as PackagePolicy[]) + .filter((ds) => Boolean(ds.name.match(pkgPoliciesNamePattern))) + .map((ds) => parseInt(ds.name.match(pkgPoliciesNamePattern)![1], 10)) .sort(); - updatePackageConfig({ + updatePackagePolicy({ name: // For Endpoint packages, the user must fill in the name, thus we don't attempt to generate // a default one here. - // FIXME: Improve package configs name uniqueness - https://github.com/elastic/kibana/issues/72948 + // FIXME: Improve package policies name uniqueness - https://github.com/elastic/kibana/issues/72948 packageInfo.name !== 'endpoint' ? `${packageInfo.name}-${ - dsWithMatchingNames.length - ? dsWithMatchingNames[dsWithMatchingNames.length - 1] + 1 + pkgPoliciesWithMatchingNames.length + ? pkgPoliciesWithMatchingNames[pkgPoliciesWithMatchingNames.length - 1] + 1 : 1 }` : '', @@ -63,23 +63,23 @@ export const StepDefinePackageConfig: React.FunctionComponent<{ title: packageInfo.title, version: packageInfo.version, }, - inputs: packageToPackageConfigInputs(packageInfo), + inputs: packageToPackagePolicyInputs(packageInfo), }); } - // If agent config has changed, update package config's config ID and namespace - if (packageConfig.config_id !== agentConfig.id) { - updatePackageConfig({ - config_id: agentConfig.id, - namespace: agentConfig.namespace, + // If agent policy has changed, update package policy's agent policy ID and namespace + if (packagePolicy.policy_id !== agentPolicy.id) { + updatePackagePolicy({ + policy_id: agentPolicy.id, + namespace: agentPolicy.namespace, }); } }, [ - packageConfig.package, - packageConfig.config_id, - agentConfig, + packagePolicy.package, + packagePolicy.policy_id, + agentPolicy, packageInfo, - updatePackageConfig, + updatePackagePolicy, ]); return validationResults ? ( @@ -87,14 +87,14 @@ export const StepDefinePackageConfig: React.FunctionComponent<{ title={

} description={ } @@ -106,19 +106,19 @@ export const StepDefinePackageConfig: React.FunctionComponent<{ error={validationResults.name} label={ } > - updatePackageConfig({ + updatePackagePolicy({ name: e.target.value, }) } - data-test-subj="packageConfigNameInput" + data-test-subj="packagePolicyNameInput" /> @@ -126,14 +126,14 @@ export const StepDefinePackageConfig: React.FunctionComponent<{ } labelAppend={ @@ -142,9 +142,9 @@ export const StepDefinePackageConfig: React.FunctionComponent<{ error={validationResults.description} > - updatePackageConfig({ + updatePackagePolicy({ description: e.target.value, }) } @@ -162,7 +162,7 @@ export const StepDefinePackageConfig: React.FunctionComponent<{ flush="left" > @@ -171,7 +171,7 @@ export const StepDefinePackageConfig: React.FunctionComponent<{ @@ -190,7 +190,7 @@ export const StepDefinePackageConfig: React.FunctionComponent<{ error={validationResults.namespace} label={ } @@ -199,15 +199,15 @@ export const StepDefinePackageConfig: React.FunctionComponent<{ noSuggestions singleSelection={true} selectedOptions={ - packageConfig.namespace ? [{ label: packageConfig.namespace }] : [] + packagePolicy.namespace ? [{ label: packagePolicy.namespace }] : [] } onCreateOption={(newNamespace: string) => { - updatePackageConfig({ + updatePackagePolicy({ namespace: newNamespace, }); }} onChange={(newNamespaces: Array<{ label: string }>) => { - updatePackageConfig({ + updatePackagePolicy({ namespace: newNamespaces.length ? newNamespaces[0].label : '', }); }} diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/step_select_config.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/step_select_agent_policy.tsx similarity index 51% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/step_select_config.tsx rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/step_select_agent_policy.tsx index 6f06530100d716..9f48be54f866d7 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/step_select_config.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/step_select_agent_policy.tsx @@ -18,55 +18,55 @@ import { EuiLink, } from '@elastic/eui'; import { Error } from '../../../components'; -import { AgentConfig, PackageInfo, GetAgentConfigsResponseItem } from '../../../types'; -import { isPackageLimited, doesAgentConfigAlreadyIncludePackage } from '../../../services'; +import { AgentPolicy, PackageInfo, GetAgentPoliciesResponseItem } from '../../../types'; +import { isPackageLimited, doesAgentPolicyAlreadyIncludePackage } from '../../../services'; import { useGetPackageInfoByKey, - useGetAgentConfigs, - sendGetOneAgentConfig, + useGetAgentPolicies, + sendGetOneAgentPolicy, useCapabilities, useFleetStatus, } from '../../../hooks'; -import { CreateAgentConfigFlyout } from '../list_page/components'; +import { CreateAgentPolicyFlyout } from '../list_page/components'; -const AgentConfigWrapper = styled(EuiFormRow)` +const AgentPolicyWrapper = styled(EuiFormRow)` .euiFormRow__label { width: 100%; } `; // Custom styling for drop down list items due to: -// 1) the max-width and overflow properties is added to prevent long config +// 1) the max-width and overflow properties is added to prevent long agent policy // names/descriptions from overflowing the flex items // 2) max-width is built from the grow property on the flex items because the value // changes based on if Fleet is enabled/setup or not -const AgentConfigNameColumn = styled(EuiFlexItem)` +const AgentPolicyNameColumn = styled(EuiFlexItem)` max-width: ${(props) => `${((props.grow as number) / 9) * 100}%`}; overflow: hidden; `; -const AgentConfigDescriptionColumn = styled(EuiFlexItem)` +const AgentPolicyDescriptionColumn = styled(EuiFlexItem)` max-width: ${(props) => `${((props.grow as number) / 9) * 100}%`}; overflow: hidden; `; -export const StepSelectConfig: React.FunctionComponent<{ +export const StepSelectAgentPolicy: React.FunctionComponent<{ pkgkey: string; updatePackageInfo: (packageInfo: PackageInfo | undefined) => void; - agentConfig: AgentConfig | undefined; - updateAgentConfig: (config: AgentConfig | undefined) => void; + agentPolicy: AgentPolicy | undefined; + updateAgentPolicy: (agentPolicy: AgentPolicy | undefined) => void; setIsLoadingSecondStep: (isLoading: boolean) => void; -}> = ({ pkgkey, updatePackageInfo, agentConfig, updateAgentConfig, setIsLoadingSecondStep }) => { +}> = ({ pkgkey, updatePackageInfo, agentPolicy, updateAgentPolicy, setIsLoadingSecondStep }) => { const { isReady: isFleetReady } = useFleetStatus(); - // Selected config state - const [selectedConfigId, setSelectedConfigId] = useState( - agentConfig ? agentConfig.id : undefined + // Selected agent policy state + const [selectedPolicyId, setSelectedPolicyId] = useState( + agentPolicy ? agentPolicy.id : undefined ); - const [selectedConfigError, setSelectedConfigError] = useState(); + const [selectedAgentPolicyError, setSelectedAgentPolicyError] = useState(); - // Create new config flyout state + // Create new agent policy flyout state const hasWriteCapabilites = useCapabilities().write; - const [isCreateAgentConfigFlyoutOpen, setIsCreateAgentConfigFlyoutOpen] = useState( + const [isCreateAgentPolicyFlyoutOpen, setIsCreateAgentPolicyFlyoutOpen] = useState( false ); @@ -78,23 +78,23 @@ export const StepSelectConfig: React.FunctionComponent<{ } = useGetPackageInfoByKey(pkgkey); const isLimitedPackage = (packageInfoData && isPackageLimited(packageInfoData.response)) || false; - // Fetch agent configs info + // Fetch agent policies info const { - data: agentConfigsData, - error: agentConfigsError, - isLoading: isAgentConfigsLoading, - sendRequest: refreshAgentConfigs, - } = useGetAgentConfigs({ + data: agentPoliciesData, + error: agentPoliciesError, + isLoading: isAgentPoliciesLoading, + sendRequest: refreshAgentPolicies, + } = useGetAgentPolicies({ page: 1, perPage: 1000, sortField: 'name', sortOrder: 'asc', full: true, }); - const agentConfigs = agentConfigsData?.items || []; - const agentConfigsById = agentConfigs.reduce( - (acc: { [key: string]: GetAgentConfigsResponseItem }, config) => { - acc[config.id] = config; + const agentPolicies = agentPoliciesData?.items || []; + const agentPoliciesById = agentPolicies.reduce( + (acc: { [key: string]: GetAgentPoliciesResponseItem }, policy) => { + acc[policy.id] = policy; return acc; }, {} @@ -107,63 +107,63 @@ export const StepSelectConfig: React.FunctionComponent<{ } }, [packageInfoData, updatePackageInfo]); - // Update parent selected agent config state + // Update parent selected agent policy state useEffect(() => { - const fetchAgentConfigInfo = async () => { - if (selectedConfigId) { + const fetchAgentPolicyInfo = async () => { + if (selectedPolicyId) { setIsLoadingSecondStep(true); - const { data, error } = await sendGetOneAgentConfig(selectedConfigId); + const { data, error } = await sendGetOneAgentPolicy(selectedPolicyId); if (error) { - setSelectedConfigError(error); - updateAgentConfig(undefined); + setSelectedAgentPolicyError(error); + updateAgentPolicy(undefined); } else if (data && data.item) { - setSelectedConfigError(undefined); - updateAgentConfig(data.item); + setSelectedAgentPolicyError(undefined); + updateAgentPolicy(data.item); } } else { - setSelectedConfigError(undefined); - updateAgentConfig(undefined); + setSelectedAgentPolicyError(undefined); + updateAgentPolicy(undefined); } setIsLoadingSecondStep(false); }; - if (!agentConfig || selectedConfigId !== agentConfig.id) { - fetchAgentConfigInfo(); + if (!agentPolicy || selectedPolicyId !== agentPolicy.id) { + fetchAgentPolicyInfo(); } - }, [selectedConfigId, agentConfig, updateAgentConfig, setIsLoadingSecondStep]); + }, [selectedPolicyId, agentPolicy, updateAgentPolicy, setIsLoadingSecondStep]); - const agentConfigOptions: Array> = packageInfoData - ? agentConfigs.map((agentConf) => { + const agentPolicyOptions: Array> = packageInfoData + ? agentPolicies.map((agentConf) => { const alreadyHasLimitedPackage = (isLimitedPackage && - doesAgentConfigAlreadyIncludePackage(agentConf, packageInfoData.response.name)) || + doesAgentPolicyAlreadyIncludePackage(agentConf, packageInfoData.response.name)) || false; return { label: agentConf.name, value: agentConf.id, disabled: alreadyHasLimitedPackage, - 'data-test-subj': 'agentConfigItem', + 'data-test-subj': 'agentPolicyItem', }; }) : []; - const selectedConfigOption = agentConfigOptions.find( - (option) => option.value === selectedConfigId + const selectedAgentPolicyOption = agentPolicyOptions.find( + (option) => option.value === selectedPolicyId ); - // Try to select default agent config + // Try to select default agent policy useEffect(() => { - if (!selectedConfigId && agentConfigs.length && agentConfigOptions.length) { - const defaultAgentConfig = agentConfigs.find((config) => config.is_default); - if (defaultAgentConfig) { - const defaultAgentConfigOption = agentConfigOptions.find( - (option) => option.value === defaultAgentConfig.id + if (!selectedPolicyId && agentPolicies.length && agentPolicyOptions.length) { + const defaultAgentPolicy = agentPolicies.find((policy) => policy.is_default); + if (defaultAgentPolicy) { + const defaultAgentPolicyOption = agentPolicyOptions.find( + (option) => option.value === defaultAgentPolicy.id ); - if (defaultAgentConfigOption && !defaultAgentConfigOption.disabled) { - setSelectedConfigId(defaultAgentConfig.id); + if (defaultAgentPolicyOption && !defaultAgentPolicyOption.disabled) { + setSelectedPolicyId(defaultAgentPolicy.id); } } } - }, [agentConfigs, agentConfigOptions, selectedConfigId]); + }, [agentPolicies, agentPolicyOptions, selectedPolicyId]); // Display package error if there is one if (packageInfoError) { @@ -171,7 +171,7 @@ export const StepSelectConfig: React.FunctionComponent<{ } @@ -180,31 +180,31 @@ export const StepSelectConfig: React.FunctionComponent<{ ); } - // Display agent configs list error if there is one - if (agentConfigsError) { + // Display agent policies list error if there is one + if (agentPoliciesError) { return ( } - error={agentConfigsError} + error={agentPoliciesError} /> ); } return ( <> - {isCreateAgentConfigFlyoutOpen ? ( + {isCreateAgentPolicyFlyoutOpen ? ( - { - setIsCreateAgentConfigFlyoutOpen(false); - if (newAgentConfig) { - refreshAgentConfigs(); - setSelectedConfigId(newAgentConfig.id); + { + setIsCreateAgentPolicyFlyoutOpen(false); + if (newAgentPolicy) { + refreshAgentPolicies(); + setSelectedPolicyId(newAgentPolicy.id); } }} ownFocus={true} @@ -213,25 +213,25 @@ export const StepSelectConfig: React.FunctionComponent<{ ) : null} -
setIsCreateAgentConfigFlyoutOpen(true)} + onClick={() => setIsCreateAgentPolicyFlyoutOpen(true)} >
@@ -239,12 +239,12 @@ export const StepSelectConfig: React.FunctionComponent<{
} helpText={ - isFleetReady && selectedConfigId ? ( + isFleetReady && selectedPolicyId ? ( ) : null @@ -252,35 +252,35 @@ export const StepSelectConfig: React.FunctionComponent<{ > ) => { return ( - + {option.label} - - + + - {agentConfigsById[option.value!].description} + {agentPoliciesById[option.value!].description} - + {isFleetReady ? ( @@ -289,31 +289,31 @@ export const StepSelectConfig: React.FunctionComponent<{ ); }} - selectedOptions={selectedConfigOption ? [selectedConfigOption] : []} + selectedOptions={selectedAgentPolicyOption ? [selectedAgentPolicyOption] : []} onChange={(options) => { const selectedOption = options[0] || undefined; if (selectedOption) { - if (selectedOption.value !== selectedConfigId) { - setSelectedConfigId(selectedOption.value); + if (selectedOption.value !== selectedPolicyId) { + setSelectedPolicyId(selectedOption.value); } } else { - setSelectedConfigId(undefined); + setSelectedPolicyId(undefined); } }} /> - +
- {/* Display selected agent config error if there is one */} - {selectedConfigError ? ( + {/* Display selected agent policy error if there is one */} + {selectedAgentPolicyError ? ( } - error={selectedConfigError} + error={selectedAgentPolicyError} /> ) : null} diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/step_select_package.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/step_select_package.tsx similarity index 80% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/step_select_package.tsx rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/step_select_package.tsx index 048ae101fcd6f6..704455b21d64a7 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/step_select_package.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/step_select_package.tsx @@ -8,9 +8,9 @@ import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; import { EuiFlexGroup, EuiFlexItem, EuiSelectable, EuiSpacer } from '@elastic/eui'; import { Error } from '../../../components'; -import { AgentConfig, PackageInfo, PackageConfig, GetPackagesResponse } from '../../../types'; +import { AgentPolicy, PackageInfo, PackagePolicy, GetPackagesResponse } from '../../../types'; import { - useGetOneAgentConfig, + useGetOneAgentPolicy, useGetPackages, useGetLimitedPackages, sendGetPackageInfoByKey, @@ -18,14 +18,14 @@ import { import { PackageIcon } from '../../../components/package_icon'; export const StepSelectPackage: React.FunctionComponent<{ - agentConfigId: string; - updateAgentConfig: (config: AgentConfig | undefined) => void; + agentPolicyId: string; + updateAgentPolicy: (agentPolicy: AgentPolicy | undefined) => void; packageInfo?: PackageInfo; updatePackageInfo: (packageInfo: PackageInfo | undefined) => void; setIsLoadingSecondStep: (isLoading: boolean) => void; }> = ({ - agentConfigId, - updateAgentConfig, + agentPolicyId, + updateAgentPolicy, packageInfo, updatePackageInfo, setIsLoadingSecondStep, @@ -36,15 +36,15 @@ export const StepSelectPackage: React.FunctionComponent<{ ); const [selectedPkgError, setSelectedPkgError] = useState(); - // Fetch agent config info + // Fetch agent policy info const { - data: agentConfigData, - error: agentConfigError, - isLoading: isAgentConfigsLoading, - } = useGetOneAgentConfig(agentConfigId); + data: agentPolicyData, + error: agentPolicyError, + isLoading: isAgentPoliciesLoading, + } = useGetOneAgentPolicy(agentPolicyId); // Fetch packages info - // Filter out limited packages already part of selected agent config + // Filter out limited packages already part of selected agent policy const [packages, setPackages] = useState([]); const { data: packagesData, @@ -56,22 +56,22 @@ export const StepSelectPackage: React.FunctionComponent<{ isLoading: isLimitedPackagesLoading, } = useGetLimitedPackages(); useEffect(() => { - if (packagesData?.response && limitedPackagesData?.response && agentConfigData?.item) { + if (packagesData?.response && limitedPackagesData?.response && agentPolicyData?.item) { const allPackages = packagesData.response; const limitedPackages = limitedPackagesData.response; - const usedLimitedPackages = (agentConfigData.item.package_configs as PackageConfig[]) - .map((packageConfig) => packageConfig.package?.name || '') + const usedLimitedPackages = (agentPolicyData.item.package_policies as PackagePolicy[]) + .map((packagePolicy) => packagePolicy.package?.name || '') .filter((pkgName) => limitedPackages.includes(pkgName)); setPackages(allPackages.filter((pkg) => !usedLimitedPackages.includes(pkg.name))); } - }, [packagesData, limitedPackagesData, agentConfigData]); + }, [packagesData, limitedPackagesData, agentPolicyData]); - // Update parent agent config state + // Update parent agent policy state useEffect(() => { - if (agentConfigData && agentConfigData.item) { - updateAgentConfig(agentConfigData.item); + if (agentPolicyData && agentPolicyData.item) { + updateAgentPolicy(agentPolicyData.item); } - }, [agentConfigData, updateAgentConfig]); + }, [agentPolicyData, updateAgentPolicy]); // Update parent selected package state useEffect(() => { @@ -97,17 +97,17 @@ export const StepSelectPackage: React.FunctionComponent<{ } }, [selectedPkgKey, packageInfo, updatePackageInfo, setIsLoadingSecondStep]); - // Display agent config error if there is one - if (agentConfigError) { + // Display agent policy error if there is one + if (agentPolicyError) { return ( } - error={agentConfigError} + error={agentPolicyError} /> ); } @@ -118,7 +118,7 @@ export const StepSelectPackage: React.FunctionComponent<{ } @@ -134,7 +134,7 @@ export const StepSelectPackage: React.FunctionComponent<{ searchable allowExclusions={false} singleSelection={true} - isLoading={isPackagesLoading || isLimitedPackagesLoading || isAgentConfigsLoading} + isLoading={isPackagesLoading || isLimitedPackagesLoading || isAgentPoliciesLoading} options={packages.map(({ title, name, version, icons }) => { const pkgkey = `${name}-${version}`; return { @@ -157,7 +157,7 @@ export const StepSelectPackage: React.FunctionComponent<{ }} searchProps={{ placeholder: i18n.translate( - 'xpack.ingestManager.createPackageConfig.stepSelectPackage.filterPackagesInputPlaceholder', + 'xpack.ingestManager.createPackagePolicy.stepSelectPackage.filterPackagesInputPlaceholder', { defaultMessage: 'Search for integrations', } @@ -190,7 +190,7 @@ export const StepSelectPackage: React.FunctionComponent<{ } diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/types.ts b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/types.ts similarity index 68% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/types.ts rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/types.ts index 5386ff17fe96b1..c6e16c2cb4d970 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/types.ts +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/create_package_policy_page/types.ts @@ -4,5 +4,5 @@ * you may not use this file except in compliance with the Elastic License. */ -export type CreatePackageConfigFrom = 'package' | 'config' | 'edit'; -export type PackageConfigFormState = 'VALID' | 'INVALID' | 'CONFIRM' | 'LOADING' | 'SUBMITTED'; +export type CreatePackagePolicyFrom = 'package' | 'policy' | 'edit'; +export type PackagePolicyFormState = 'VALID' | 'INVALID' | 'CONFIRM' | 'LOADING' | 'SUBMITTED'; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/details_page/components/index.ts b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/details_page/components/index.ts new file mode 100644 index 00000000000000..9ea1e77dce4761 --- /dev/null +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/details_page/components/index.ts @@ -0,0 +1,8 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +export { PackagePoliciesTable } from './package_policies/package_policies_table'; +export { PackagePoliciesView } from './package_policies'; +export { SettingsView } from './settings'; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/details_page/components/package_policies/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/details_page/components/package_policies/index.tsx new file mode 100644 index 00000000000000..494407b93f2a84 --- /dev/null +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/details_page/components/package_policies/index.tsx @@ -0,0 +1,23 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { memo } from 'react'; +import { AgentPolicy, PackagePolicy } from '../../../../../types'; +import { NoPackagePolicies } from './no_package_policies'; +import { PackagePoliciesTable } from './package_policies_table'; + +export const PackagePoliciesView = memo<{ agentPolicy: AgentPolicy }>(({ agentPolicy }) => { + if (agentPolicy.package_policies.length === 0) { + return ; + } + + return ( + + ); +}); diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/package_configs/no_package_configs.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/details_page/components/package_policies/no_package_policies.tsx similarity index 68% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/package_configs/no_package_configs.tsx rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/details_page/components/package_policies/no_package_policies.tsx index ad75c707836980..b84466ee073ebe 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/package_configs/no_package_configs.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/details_page/components/package_policies/no_package_policies.tsx @@ -8,7 +8,7 @@ import { FormattedMessage } from '@kbn/i18n/react'; import { EuiButton, EuiEmptyPrompt } from '@elastic/eui'; import { useCapabilities, useLink } from '../../../../../hooks'; -export const NoPackageConfigs = memo<{ configId: string }>(({ configId }) => { +export const NoPackagePolicies = memo<{ policyId: string }>(({ policyId }) => { const { getHref } = useLink(); const hasWriteCapabilities = useCapabilities().write; @@ -18,25 +18,25 @@ export const NoPackageConfigs = memo<{ configId: string }>(({ configId }) => { title={

} body={ } actions={ diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/package_configs/package_configs_table.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/details_page/components/package_policies/package_policies_table.tsx similarity index 62% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/package_configs/package_configs_table.tsx rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/details_page/components/package_policies/package_policies_table.tsx index 1aa0fd1220833b..fa9ce249354297 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/package_configs/package_configs_table.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/details_page/components/package_policies/package_policies_table.tsx @@ -15,13 +15,13 @@ import { EuiFlexGroup, EuiFlexItem, } from '@elastic/eui'; -import { AgentConfig, PackageConfig } from '../../../../../types'; +import { AgentPolicy, PackagePolicy } from '../../../../../types'; import { PackageIcon, ContextMenuActions } from '../../../../../components'; -import { PackageConfigDeleteProvider, DangerEuiContextMenuItem } from '../../../components'; +import { PackagePolicyDeleteProvider, DangerEuiContextMenuItem } from '../../../components'; import { useCapabilities, useLink } from '../../../../../hooks'; -import { useConfigRefresh } from '../../hooks'; +import { useAgentPolicyRefresh } from '../../hooks'; -interface InMemoryPackageConfig extends PackageConfig { +interface InMemoryPackagePolicy extends PackagePolicy { inputTypes: string[]; packageName?: string; packageTitle?: string; @@ -29,11 +29,11 @@ interface InMemoryPackageConfig extends PackageConfig { } interface Props { - packageConfigs: PackageConfig[]; - config: AgentConfig; + packagePolicies: PackagePolicy[]; + agentPolicy: AgentPolicy; // Pass through props to InMemoryTable - loading?: EuiInMemoryTableProps['loading']; - message?: EuiInMemoryTableProps['message']; + loading?: EuiInMemoryTableProps['loading']; + message?: EuiInMemoryTableProps['message']; } interface FilterOption { @@ -44,29 +44,29 @@ interface FilterOption { const stringSortAscending = (a: string, b: string): number => a.localeCompare(b); const toFilterOption = (value: string): FilterOption => ({ name: value, value }); -export const PackageConfigsTable: React.FunctionComponent = ({ - packageConfigs: originalPackageConfigs, - config, +export const PackagePoliciesTable: React.FunctionComponent = ({ + packagePolicies: originalPackagePolicies, + agentPolicy, ...rest }) => { const { getHref } = useLink(); const hasWriteCapabilities = useCapabilities().write; - const refreshConfig = useConfigRefresh(); + const refreshAgentPolicy = useAgentPolicyRefresh(); - // With the package configs provided on input, generate the list of package configs + // With the package policies provided on input, generate the list of package policies // used in the InMemoryTable (flattens some values for search) as well as // the list of options that will be used in the filters dropdowns - const [packageConfigs, namespaces, inputTypes] = useMemo((): [ - InMemoryPackageConfig[], + const [packagePolicies, namespaces, inputTypes] = useMemo((): [ + InMemoryPackagePolicy[], FilterOption[], FilterOption[] ] => { const namespacesValues: string[] = []; const inputTypesValues: string[] = []; - const mappedPackageConfigs = originalPackageConfigs.map( - (packageConfig) => { - if (packageConfig.namespace && !namespacesValues.includes(packageConfig.namespace)) { - namespacesValues.push(packageConfig.namespace); + const mappedPackagePolicies = originalPackagePolicies.map( + (packagePolicy) => { + if (packagePolicy.namespace && !namespacesValues.includes(packagePolicy.namespace)) { + namespacesValues.push(packagePolicy.namespace); } const dsInputTypes: string[] = []; @@ -74,11 +74,11 @@ export const PackageConfigsTable: React.FunctionComponent = ({ dsInputTypes.sort(stringSortAscending); return { - ...packageConfig, + ...packagePolicy, inputTypes: dsInputTypes, - packageName: packageConfig.package?.name ?? '', - packageTitle: packageConfig.package?.title ?? '', - packageVersion: packageConfig.package?.version ?? '', + packageName: packagePolicy.package?.name ?? '', + packageTitle: packagePolicy.package?.title ?? '', + packageVersion: packagePolicy.package?.version ?? '', }; } ); @@ -87,19 +87,19 @@ export const PackageConfigsTable: React.FunctionComponent = ({ inputTypesValues.sort(stringSortAscending); return [ - mappedPackageConfigs, + mappedPackagePolicies, namespacesValues.map(toFilterOption), inputTypesValues.map(toFilterOption), ]; - }, [originalPackageConfigs]); + }, [originalPackagePolicies]); const columns = useMemo( - (): EuiInMemoryTableProps['columns'] => [ + (): EuiInMemoryTableProps['columns'] => [ { field: 'name', sortable: true, name: i18n.translate( - 'xpack.ingestManager.configDetails.packageConfigsTable.nameColumnTitle', + 'xpack.ingestManager.policyDetails.packagePoliciesTable.nameColumnTitle', { defaultMessage: 'Name', } @@ -113,7 +113,7 @@ export const PackageConfigsTable: React.FunctionComponent = ({ { field: 'description', name: i18n.translate( - 'xpack.ingestManager.configDetails.packageConfigsTable.descriptionColumnTitle', + 'xpack.ingestManager.policyDetails.packagePoliciesTable.descriptionColumnTitle', { defaultMessage: 'Description', } @@ -128,19 +128,19 @@ export const PackageConfigsTable: React.FunctionComponent = ({ field: 'packageTitle', sortable: true, name: i18n.translate( - 'xpack.ingestManager.configDetails.packageConfigsTable.packageNameColumnTitle', + 'xpack.ingestManager.policyDetails.packagePoliciesTable.packageNameColumnTitle', { defaultMessage: 'Integration', } ), - render(packageTitle: string, packageConfig: InMemoryPackageConfig) { + render(packageTitle: string, packagePolicy: InMemoryPackagePolicy) { return ( - {packageConfig.package && ( + {packagePolicy.package && ( @@ -154,36 +154,36 @@ export const PackageConfigsTable: React.FunctionComponent = ({ { field: 'namespace', name: i18n.translate( - 'xpack.ingestManager.configDetails.packageConfigsTable.namespaceColumnTitle', + 'xpack.ingestManager.policyDetails.packagePoliciesTable.namespaceColumnTitle', { defaultMessage: 'Namespace', } ), - render: (namespace: InMemoryPackageConfig['namespace']) => { + render: (namespace: InMemoryPackagePolicy['namespace']) => { return namespace ? {namespace} : ''; }, }, { name: i18n.translate( - 'xpack.ingestManager.configDetails.packageConfigsTable.actionsColumnTitle', + 'xpack.ingestManager.policyDetails.packagePoliciesTable.actionsColumnTitle', { defaultMessage: 'Actions', } ), actions: [ { - render: (packageConfig: InMemoryPackageConfig) => ( + render: (packagePolicy: InMemoryPackagePolicy) => ( {}} - // key="packageConfigView" + // key="packagePolicyView" // > // // , @@ -191,41 +191,41 @@ export const PackageConfigsTable: React.FunctionComponent = ({ disabled={!hasWriteCapabilities} icon="pencil" href={getHref('edit_integration', { - configId: config.id, - packageConfigId: packageConfig.id, + policyId: agentPolicy.id, + packagePolicyId: packagePolicy.id, })} - key="packageConfigEdit" + key="packagePolicyEdit" > , - // FIXME: implement Copy package config action - // {}} key="packageConfigCopy"> + // FIXME: implement Copy package policy action + // {}} key="packagePolicyCopy"> // // , - - {(deletePackageConfigsPrompt) => { + + {(deletePackagePoliciesPrompt) => { return ( { - deletePackageConfigsPrompt([packageConfig.id], refreshConfig); + deletePackagePoliciesPrompt([packagePolicy.id], refreshAgentPolicy); }} > ); }} - , + , ]} /> ), @@ -233,13 +233,13 @@ export const PackageConfigsTable: React.FunctionComponent = ({ ], }, ], - [config, getHref, hasWriteCapabilities, refreshConfig] + [agentPolicy, getHref, hasWriteCapabilities, refreshAgentPolicy] ); return ( - + itemId="id" - items={packageConfigs} + items={packagePolicies} columns={columns} sorting={{ sort: { @@ -251,13 +251,13 @@ export const PackageConfigsTable: React.FunctionComponent = ({ search={{ toolsRight: [ , diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/settings/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/details_page/components/settings/index.tsx similarity index 73% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/settings/index.tsx rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/details_page/components/settings/index.tsx index dfdd63bd984dda..766bdc2e2c1930 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/components/settings/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/details_page/components/settings/index.tsx @@ -9,21 +9,21 @@ import styled from 'styled-components'; import { EuiBottomBar, EuiFlexGroup, EuiFlexItem, EuiButtonEmpty, EuiButton } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; -import { AgentConfig } from '../../../../../types'; +import { AgentPolicy } from '../../../../../types'; import { useLink, useCore, useCapabilities, - sendUpdateAgentConfig, + sendUpdateAgentPolicy, useConfig, sendGetAgentStatus, } from '../../../../../hooks'; import { - AgentConfigForm, - agentConfigFormValidation, - ConfirmDeployConfigModal, + AgentPolicyForm, + agentPolicyFormValidation, + ConfirmDeployAgentPolicyModal, } from '../../../components'; -import { useConfigRefresh } from '../../hooks'; +import { useAgentPolicyRefresh } from '../../hooks'; const FormWrapper = styled.div` max-width: 800px; @@ -31,8 +31,8 @@ const FormWrapper = styled.div` margin-left: auto; `; -export const ConfigSettingsView = memo<{ config: AgentConfig }>( - ({ config: originalAgentConfig }) => { +export const SettingsView = memo<{ agentPolicy: AgentPolicy }>( + ({ agentPolicy: originalAgentPolicy }) => { const { notifications, chrome: { getIsNavDrawerLocked$ }, @@ -44,16 +44,16 @@ export const ConfigSettingsView = memo<{ config: AgentConfig }>( const history = useHistory(); const { getPath } = useLink(); const hasWriteCapabilites = useCapabilities().write; - const refreshConfig = useConfigRefresh(); + const refreshAgentPolicy = useAgentPolicyRefresh(); const [isNavDrawerLocked, setIsNavDrawerLocked] = useState(false); - const [agentConfig, setAgentConfig] = useState({ - ...originalAgentConfig, + const [agentPolicy, setAgentPolicy] = useState({ + ...originalAgentPolicy, }); const [isLoading, setIsLoading] = useState(false); const [hasChanges, setHasChanges] = useState(false); const [agentCount, setAgentCount] = useState(0); const [withSysMonitoring, setWithSysMonitoring] = useState(true); - const validation = agentConfigFormValidation(agentConfig); + const validation = agentPolicyFormValidation(agentPolicy); useEffect(() => { const subscription = getIsNavDrawerLocked$().subscribe((newIsNavDrawerLocked: boolean) => { @@ -63,20 +63,20 @@ export const ConfigSettingsView = memo<{ config: AgentConfig }>( return () => subscription.unsubscribe(); }); - const updateAgentConfig = (updatedFields: Partial) => { - setAgentConfig({ - ...agentConfig, + const updateAgentPolicy = (updatedFields: Partial) => { + setAgentPolicy({ + ...agentPolicy, ...updatedFields, }); setHasChanges(true); }; - const submitUpdateAgentConfig = async () => { + const submitUpdateAgentPolicy = async () => { setIsLoading(true); try { // eslint-disable-next-line @typescript-eslint/naming-convention - const { name, description, namespace, monitoring_enabled } = agentConfig; - const { data, error } = await sendUpdateAgentConfig(agentConfig.id, { + const { name, description, namespace, monitoring_enabled } = agentPolicy; + const { data, error } = await sendUpdateAgentPolicy(agentPolicy.id, { name, description, namespace, @@ -84,26 +84,26 @@ export const ConfigSettingsView = memo<{ config: AgentConfig }>( }); if (data?.success) { notifications.toasts.addSuccess( - i18n.translate('xpack.ingestManager.editAgentConfig.successNotificationTitle', { + i18n.translate('xpack.ingestManager.editAgentPolicy.successNotificationTitle', { defaultMessage: "Successfully updated '{name}' settings", - values: { name: agentConfig.name }, + values: { name: agentPolicy.name }, }) ); - refreshConfig(); + refreshAgentPolicy(); setHasChanges(false); } else { notifications.toasts.addDanger( error ? error.message - : i18n.translate('xpack.ingestManager.editAgentConfig.errorNotificationTitle', { - defaultMessage: 'Unable to update agent config', + : i18n.translate('xpack.ingestManager.editAgentPolicy.errorNotificationTitle', { + defaultMessage: 'Unable to update agent policy', }) ); } } catch (e) { notifications.toasts.addDanger( - i18n.translate('xpack.ingestManager.editAgentConfig.errorNotificationTitle', { - defaultMessage: 'Unable to update agent config', + i18n.translate('xpack.ingestManager.editAgentPolicy.errorNotificationTitle', { + defaultMessage: 'Unable to update agent policy', }) ); } @@ -114,26 +114,26 @@ export const ConfigSettingsView = memo<{ config: AgentConfig }>( // Retrieve agent count if fleet is enabled if (isFleetEnabled) { setIsLoading(true); - const { data } = await sendGetAgentStatus({ configId: agentConfig.id }); + const { data } = await sendGetAgentStatus({ policyId: agentPolicy.id }); if (data?.results.total) { setAgentCount(data.results.total); } else { - await submitUpdateAgentConfig(); + await submitUpdateAgentPolicy(); } } else { - await submitUpdateAgentConfig(); + await submitUpdateAgentPolicy(); } }; return ( {agentCount ? ( - { setAgentCount(0); - submitUpdateAgentConfig(); + submitUpdateAgentPolicy(); }} onCancel={() => { setAgentCount(0); @@ -141,15 +141,15 @@ export const ConfigSettingsView = memo<{ config: AgentConfig }>( }} /> ) : null} - setWithSysMonitoring(newValue)} validation={validation} isEditing={true} onDelete={() => { - history.push(getPath('configurations_list')); + history.push(getPath('policies_list')); }} /> {/* TODO #64541 - Remove classes */} @@ -166,7 +166,7 @@ export const ConfigSettingsView = memo<{ config: AgentConfig }>( @@ -176,12 +176,12 @@ export const ConfigSettingsView = memo<{ config: AgentConfig }>( { - setAgentConfig({ ...originalAgentConfig }); + setAgentPolicy({ ...originalAgentPolicy }); setHasChanges(false); }} > @@ -199,12 +199,12 @@ export const ConfigSettingsView = memo<{ config: AgentConfig }>( > {isLoading ? ( ) : ( )} diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/hooks/index.ts b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/details_page/hooks/index.ts similarity index 80% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/hooks/index.ts rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/details_page/hooks/index.ts index 76c6d64eb9e07a..4bdf49d5764ea1 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/hooks/index.ts +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/details_page/hooks/index.ts @@ -4,4 +4,4 @@ * you may not use this file except in compliance with the Elastic License. */ export { useGetAgentStatus, AgentStatusRefreshContext } from './use_agent_status'; -export { ConfigRefreshContext, useConfigRefresh } from './use_config'; +export { AgentPolicyRefreshContext, useAgentPolicyRefresh } from './use_config'; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/hooks/use_agent_status.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/details_page/hooks/use_agent_status.tsx similarity index 93% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/hooks/use_agent_status.tsx rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/details_page/hooks/use_agent_status.tsx index 214deb81f535c8..71dcd728d5d1bb 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/hooks/use_agent_status.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/details_page/hooks/use_agent_status.tsx @@ -11,11 +11,11 @@ import { UseRequestConfig } from '../../../../hooks/use_request/use_request'; type RequestOptions = Pick, 'pollIntervalMs'>; -export function useGetAgentStatus(configId?: string, options?: RequestOptions) { +export function useGetAgentStatus(policyId?: string, options?: RequestOptions) { const agentStatusRequest = useRequest({ path: agentRouteService.getStatusPath(), query: { - configId, + policyId, }, method: 'get', ...options, diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/hooks/use_config.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/details_page/hooks/use_config.tsx similarity index 59% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/hooks/use_config.tsx rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/details_page/hooks/use_config.tsx index b61986e7abb4fd..83004af7a79eea 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/hooks/use_config.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/details_page/hooks/use_config.tsx @@ -5,8 +5,8 @@ */ import React from 'react'; -export const ConfigRefreshContext = React.createContext({ refresh: () => {} }); +export const AgentPolicyRefreshContext = React.createContext({ refresh: () => {} }); -export function useConfigRefresh() { - return React.useContext(ConfigRefreshContext).refresh; +export function useAgentPolicyRefresh() { + return React.useContext(AgentPolicyRefreshContext).refresh; } diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/details_page/index.tsx similarity index 64% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/index.tsx rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/details_page/index.tsx index b87bd66cce0eaf..4c317c54c68c48 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/details_page/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/details_page/index.tsx @@ -20,14 +20,14 @@ import { } from '@elastic/eui'; import { Props as EuiTabProps } from '@elastic/eui/src/components/tabs/tab'; import styled from 'styled-components'; -import { AgentConfig, AgentConfigDetailsDeployAgentAction } from '../../../types'; +import { AgentPolicy, AgentPolicyDetailsDeployAgentAction } from '../../../types'; import { PAGE_ROUTING_PATHS } from '../../../constants'; -import { useGetOneAgentConfig, useLink, useBreadcrumbs, useCore } from '../../../hooks'; +import { useGetOneAgentPolicy, useLink, useBreadcrumbs, useCore } from '../../../hooks'; import { Loading, Error } from '../../../components'; import { WithHeaderLayout } from '../../../layouts'; -import { ConfigRefreshContext, useGetAgentStatus, AgentStatusRefreshContext } from './hooks'; -import { LinkedAgentCount, AgentConfigActionMenu } from '../components'; -import { ConfigPackageConfigsView, ConfigSettingsView } from './components'; +import { AgentPolicyRefreshContext, useGetAgentStatus, AgentStatusRefreshContext } from './hooks'; +import { LinkedAgentCount, AgentPolicyActionMenu } from '../components'; +import { PackagePoliciesView, SettingsView } from './components'; import { useIntraAppState } from '../../../hooks/use_intra_app_state'; const Divider = styled.div` @@ -36,22 +36,22 @@ const Divider = styled.div` border-left: ${(props) => props.theme.eui.euiBorderThin}; `; -export const AgentConfigDetailsPage: React.FunctionComponent = () => { +export const AgentPolicyDetailsPage: React.FunctionComponent = () => { const { - params: { configId, tabId = '' }, - } = useRouteMatch<{ configId: string; tabId?: string }>(); + params: { policyId, tabId = '' }, + } = useRouteMatch<{ policyId: string; tabId?: string }>(); const history = useHistory(); const { getHref, getPath } = useLink(); - const agentConfigRequest = useGetOneAgentConfig(configId); - const agentConfig = agentConfigRequest.data ? agentConfigRequest.data.item : null; - const { isLoading, error, sendRequest: refreshAgentConfig } = agentConfigRequest; - const [redirectToAgentConfigList] = useState(false); - const agentStatusRequest = useGetAgentStatus(configId); + const agentPolicyRequest = useGetOneAgentPolicy(policyId); + const agentPolicy = agentPolicyRequest.data ? agentPolicyRequest.data.item : null; + const { isLoading, error, sendRequest: refreshAgentPolicy } = agentPolicyRequest; + const [redirectToAgentPolicyList] = useState(false); + const agentStatusRequest = useGetAgentStatus(policyId); const { refreshAgentStatus } = agentStatusRequest; const { application: { navigateToApp }, } = useCore(); - const routeState = useIntraAppState(); + const routeState = useIntraAppState(); const agentStatus = agentStatusRequest.data?.results; const queryParams = new URLSearchParams(useLocation().search); const openEnrollmentFlyoutOpenByDefault = queryParams.get('openEnrollmentFlyout') === 'true'; @@ -62,25 +62,25 @@ export const AgentConfigDetailsPage: React.FunctionComponent = () => {

- {(agentConfig && agentConfig.name) || ( + {(agentPolicy && agentPolicy.name) || ( )} @@ -88,17 +88,17 @@ export const AgentConfigDetailsPage: React.FunctionComponent = () => { - {agentConfig && agentConfig.description ? ( + {agentPolicy && agentPolicy.description ? ( - {agentConfig.description} + {agentPolicy.description} ) : null} ), - [getHref, agentConfig, configId] + [getHref, agentPolicy, policyId] ); const enrollmentCancelClickHandler = useCallback(() => { @@ -109,26 +109,26 @@ export const AgentConfigDetailsPage: React.FunctionComponent = () => { const headerRightContent = useMemo( () => - agentConfig ? ( + agentPolicy ? ( {[ { - label: i18n.translate('xpack.ingestManager.configDetails.summary.revision', { + label: i18n.translate('xpack.ingestManager.policyDetails.summary.revision', { defaultMessage: 'Revision', }), - content: agentConfig?.revision ?? 0, + content: agentPolicy?.revision ?? 0, }, { isDivider: true }, { - label: i18n.translate('xpack.ingestManager.configDetails.summary.package_configs', { + label: i18n.translate('xpack.ingestManager.policyDetails.summary.integrations', { defaultMessage: 'Integrations', }), content: ( @@ -136,25 +136,25 @@ export const AgentConfigDetailsPage: React.FunctionComponent = () => { }, { isDivider: true }, { - label: i18n.translate('xpack.ingestManager.configDetails.summary.usedBy', { + label: i18n.translate('xpack.ingestManager.policyDetails.summary.usedBy', { defaultMessage: 'Used by', }), content: ( ), }, { isDivider: true }, { - label: i18n.translate('xpack.ingestManager.configDetails.summary.lastUpdated', { + label: i18n.translate('xpack.ingestManager.policyDetails.summary.lastUpdated', { defaultMessage: 'Last updated on', }), content: - (agentConfig && ( + (agentPolicy && ( { }, { isDivider: true }, { - content: agentConfig && ( - { - history.push(getPath('configuration_details', { configId: newAgentConfig.id })); + onCopySuccess={(newAgentPolicy: AgentPolicy) => { + history.push(getPath('policy_details', { policyId: newAgentPolicy.id })); }} enrollmentFlyoutOpenByDefault={openEnrollmentFlyoutOpenByDefault} onCancelEnrollment={ @@ -201,32 +201,32 @@ export const AgentConfigDetailsPage: React.FunctionComponent = () => { ) : undefined, /* eslint-disable-next-line react-hooks/exhaustive-deps */ - [agentConfig, configId, agentStatus] + [agentPolicy, policyId, agentStatus] ); const headerTabs = useMemo(() => { return [ { id: 'integrations', - name: i18n.translate('xpack.ingestManager.configDetails.subTabs.packageConfigsTabText', { + name: i18n.translate('xpack.ingestManager.policyDetails.subTabs.packagePoliciesTabText', { defaultMessage: 'Integrations', }), - href: getHref('configuration_details', { configId, tabId: 'integrations' }), + href: getHref('policy_details', { policyId, tabId: 'integrations' }), isSelected: tabId === '' || tabId === 'integrations', }, { id: 'settings', - name: i18n.translate('xpack.ingestManager.configDetails.subTabs.settingsTabText', { + name: i18n.translate('xpack.ingestManager.policyDetails.subTabs.settingsTabText', { defaultMessage: 'Settings', }), - href: getHref('configuration_details', { configId, tabId: 'settings' }), + href: getHref('policy_details', { policyId, tabId: 'settings' }), isSelected: tabId === 'settings', }, ]; - }, [getHref, configId, tabId]); + }, [getHref, policyId, tabId]); const content = useMemo(() => { - if (redirectToAgentConfigList) { + if (redirectToAgentPolicyList) { return ; } @@ -239,8 +239,8 @@ export const AgentConfigDetailsPage: React.FunctionComponent = () => { } error={error} @@ -248,30 +248,30 @@ export const AgentConfigDetailsPage: React.FunctionComponent = () => { ); } - if (!agentConfig) { + if (!agentPolicy) { return ( } - error={i18n.translate('xpack.ingestManager.configDetails.configNotFoundErrorTitle', { - defaultMessage: "Config '{id}' not found", + error={i18n.translate('xpack.ingestManager.policyDetails.policyNotFoundErrorTitle', { + defaultMessage: "Policy '{id}' not found", values: { - id: configId, + id: policyId, }, })} /> ); } - return ; - }, [agentConfig, configId, error, isLoading, redirectToAgentConfigList]); + return ; + }, [agentPolicy, policyId, error, isLoading, redirectToAgentPolicyList]); return ( - + { {content} - + ); }; -const AgentConfigDetailsContent: React.FunctionComponent<{ agentConfig: AgentConfig }> = ({ - agentConfig, +const AgentPolicyDetailsContent: React.FunctionComponent<{ agentPolicy: AgentPolicy }> = ({ + agentPolicy, }) => { - useBreadcrumbs('configuration_details', { configName: agentConfig.name }); + useBreadcrumbs('policy_details', { policyName: agentPolicy.name }); return ( { - return ; + return ; }} /> { - return ; + return ; }} /> diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/edit_package_config_page/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/edit_package_policy_page/index.tsx similarity index 59% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/edit_package_config_page/index.tsx rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/edit_package_policy_page/index.tsx index 3005f8d36f343c..fc3d28c9392ce4 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/edit_package_config_page/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/edit_package_policy_page/index.tsx @@ -15,34 +15,34 @@ import { EuiFlexItem, EuiSpacer, } from '@elastic/eui'; -import { AgentConfig, PackageInfo, UpdatePackageConfig } from '../../../types'; +import { AgentPolicy, PackageInfo, UpdatePackagePolicy } from '../../../types'; import { useLink, useBreadcrumbs, useCore, useConfig, - sendUpdatePackageConfig, + sendUpdatePackagePolicy, sendGetAgentStatus, - sendGetOneAgentConfig, - sendGetOnePackageConfig, + sendGetOneAgentPolicy, + sendGetOnePackagePolicy, sendGetPackageInfoByKey, } from '../../../hooks'; import { Loading, Error } from '../../../components'; -import { ConfirmDeployConfigModal } from '../components'; -import { CreatePackageConfigPageLayout } from '../create_package_config_page/components'; +import { ConfirmDeployAgentPolicyModal } from '../components'; +import { CreatePackagePolicyPageLayout } from '../create_package_policy_page/components'; import { - PackageConfigValidationResults, - validatePackageConfig, + PackagePolicyValidationResults, + validatePackagePolicy, validationHasErrors, -} from '../create_package_config_page/services'; +} from '../create_package_policy_page/services'; import { - PackageConfigFormState, - CreatePackageConfigFrom, -} from '../create_package_config_page/types'; -import { StepConfigurePackage } from '../create_package_config_page/step_configure_package'; -import { StepDefinePackageConfig } from '../create_package_config_page/step_define_package_config'; + PackagePolicyFormState, + CreatePackagePolicyFrom, +} from '../create_package_policy_page/types'; +import { StepConfigurePackagePolicy } from '../create_package_policy_page/step_configure_package'; +import { StepDefinePackagePolicy } from '../create_package_policy_page/step_define_package_policy'; -export const EditPackageConfigPage: React.FunctionComponent = () => { +export const EditPackagePolicyPage: React.FunctionComponent = () => { const { notifications, chrome: { getIsNavDrawerLocked$ }, @@ -52,7 +52,7 @@ export const EditPackageConfigPage: React.FunctionComponent = () => { fleet: { enabled: isFleetEnabled }, } = useConfig(); const { - params: { configId, packageConfigId }, + params: { policyId, packagePolicyId }, } = useRouteMatch(); const history = useHistory(); const { getHref, getPath } = useLink(); @@ -66,36 +66,36 @@ export const EditPackageConfigPage: React.FunctionComponent = () => { return () => subscription.unsubscribe(); }); - // Agent config, package info, and package config states + // Agent policy, package info, and package policy states const [isLoadingData, setIsLoadingData] = useState(true); const [loadingError, setLoadingError] = useState(); - const [agentConfig, setAgentConfig] = useState(); + const [agentPolicy, setAgentPolicy] = useState(); const [packageInfo, setPackageInfo] = useState(); - const [packageConfig, setPackageConfig] = useState({ + const [packagePolicy, setPackagePolicy] = useState({ name: '', description: '', namespace: '', - config_id: '', + policy_id: '', enabled: true, output_id: '', inputs: [], version: '', }); - // Retrieve agent config, package, and package config info + // Retrieve agent policy, package, and package policy info useEffect(() => { const getData = async () => { setIsLoadingData(true); setLoadingError(undefined); try { - const [{ data: agentConfigData }, { data: packageConfigData }] = await Promise.all([ - sendGetOneAgentConfig(configId), - sendGetOnePackageConfig(packageConfigId), + const [{ data: agentPolicyData }, { data: packagePolicyData }] = await Promise.all([ + sendGetOneAgentPolicy(policyId), + sendGetOnePackagePolicy(packagePolicyId), ]); - if (agentConfigData?.item) { - setAgentConfig(agentConfigData.item); + if (agentPolicyData?.item) { + setAgentPolicy(agentPolicyData.item); } - if (packageConfigData?.item) { + if (packagePolicyData?.item) { const { id, revision, @@ -106,11 +106,11 @@ export const EditPackageConfigPage: React.FunctionComponent = () => { updated_by, updated_at, /* eslint-enable @typescript-eslint/naming-convention */ - ...restOfPackageConfig - } = packageConfigData.item; + ...restOfPackagePolicy + } = packagePolicyData.item; // Remove `compiled_stream` from all stream info, we assign this after saving - const newPackageConfig = { - ...restOfPackageConfig, + const newPackagePolicy = { + ...restOfPackagePolicy, inputs: inputs.map((input) => { const { streams, ...restOfInput } = input; return { @@ -123,14 +123,14 @@ export const EditPackageConfigPage: React.FunctionComponent = () => { }; }), }; - setPackageConfig(newPackageConfig); - if (packageConfigData.item.package) { + setPackagePolicy(newPackagePolicy); + if (packagePolicyData.item.package) { const { data: packageData } = await sendGetPackageInfoByKey( - `${packageConfigData.item.package.name}-${packageConfigData.item.package.version}` + `${packagePolicyData.item.package.name}-${packagePolicyData.item.package.version}` ); if (packageData?.response) { setPackageInfo(packageData.response); - setValidationResults(validatePackageConfig(newPackageConfig, packageData.response)); + setValidationResults(validatePackagePolicy(newPackagePolicy, packageData.response)); setFormState('VALID'); } } @@ -141,13 +141,13 @@ export const EditPackageConfigPage: React.FunctionComponent = () => { setIsLoadingData(false); }; getData(); - }, [configId, packageConfigId]); + }, [policyId, packagePolicyId]); // Retrieve agent count const [agentCount, setAgentCount] = useState(0); useEffect(() => { const getAgentCount = async () => { - const { data } = await sendGetAgentStatus({ configId }); + const { data } = await sendGetAgentStatus({ policyId }); if (data?.results.total) { setAgentCount(data.results.total); } @@ -156,42 +156,42 @@ export const EditPackageConfigPage: React.FunctionComponent = () => { if (isFleetEnabled) { getAgentCount(); } - }, [configId, isFleetEnabled]); + }, [policyId, isFleetEnabled]); - // Package config validation state - const [validationResults, setValidationResults] = useState(); + // Package policy validation state + const [validationResults, setValidationResults] = useState(); const hasErrors = validationResults ? validationHasErrors(validationResults) : false; - // Update package config validation - const updatePackageConfigValidation = useCallback( - (newPackageConfig?: UpdatePackageConfig) => { + // Update package policy validation + const updatePackagePolicyValidation = useCallback( + (newPackagePolicy?: UpdatePackagePolicy) => { if (packageInfo) { - const newValidationResult = validatePackageConfig( - newPackageConfig || packageConfig, + const newValidationResult = validatePackagePolicy( + newPackagePolicy || packagePolicy, packageInfo ); setValidationResults(newValidationResult); // eslint-disable-next-line no-console - console.debug('Package config validation results', newValidationResult); + console.debug('Package policy validation results', newValidationResult); return newValidationResult; } }, - [packageConfig, packageInfo] + [packagePolicy, packageInfo] ); - // Update package config method - const updatePackageConfig = useCallback( - (updatedFields: Partial) => { - const newPackageConfig = { - ...packageConfig, + // Update package policy method + const updatePackagePolicy = useCallback( + (updatedFields: Partial) => { + const newPackagePolicy = { + ...packagePolicy, ...updatedFields, }; - setPackageConfig(newPackageConfig); + setPackagePolicy(newPackagePolicy); // eslint-disable-next-line no-console - console.debug('Package config updated', newPackageConfig); - const newValidationResults = updatePackageConfigValidation(newPackageConfig); + console.debug('Package policy updated', newPackagePolicy); + const newValidationResults = updatePackagePolicyValidation(newPackagePolicy); const hasValidationErrors = newValidationResults ? validationHasErrors(newValidationResults) : false; @@ -199,17 +199,17 @@ export const EditPackageConfigPage: React.FunctionComponent = () => { setFormState('VALID'); } }, - [packageConfig, updatePackageConfigValidation] + [packagePolicy, updatePackagePolicyValidation] ); // Cancel url - const cancelUrl = getHref('configuration_details', { configId }); + const cancelUrl = getHref('policy_details', { policyId }); - // Save package config - const [formState, setFormState] = useState('INVALID'); - const savePackageConfig = async () => { + // Save package policy + const [formState, setFormState] = useState('INVALID'); + const savePackagePolicy = async () => { setFormState('LOADING'); - const result = await sendUpdatePackageConfig(packageConfigId, packageConfig); + const result = await sendUpdatePackagePolicy(packagePolicyId, packagePolicy); setFormState('SUBMITTED'); return result; }; @@ -223,22 +223,22 @@ export const EditPackageConfigPage: React.FunctionComponent = () => { setFormState('CONFIRM'); return; } - const { error } = await savePackageConfig(); + const { error } = await savePackagePolicy(); if (!error) { - history.push(getPath('configuration_details', { configId })); + history.push(getPath('policy_details', { policyId })); notifications.toasts.addSuccess({ - title: i18n.translate('xpack.ingestManager.editPackageConfig.updatedNotificationTitle', { - defaultMessage: `Successfully updated '{packageConfigName}'`, + title: i18n.translate('xpack.ingestManager.editPackagePolicy.updatedNotificationTitle', { + defaultMessage: `Successfully updated '{packagePolicyName}'`, values: { - packageConfigName: packageConfig.name, + packagePolicyName: packagePolicy.name, }, }), text: - agentCount && agentConfig - ? i18n.translate('xpack.ingestManager.editPackageConfig.updatedNotificationMessage', { - defaultMessage: `Fleet will deploy updates to all agents that use the '{agentConfigName}' configuration`, + agentCount && agentPolicy + ? i18n.translate('xpack.ingestManager.editPackagePolicy.updatedNotificationMessage', { + defaultMessage: `Fleet will deploy updates to all agents that use the '{agentPolicyName}' policy`, values: { - agentConfigName: agentConfig.name, + agentPolicyName: agentPolicy.name, }, }) : undefined, @@ -246,25 +246,25 @@ export const EditPackageConfigPage: React.FunctionComponent = () => { } else { if (error.statusCode === 409) { notifications.toasts.addError(error, { - title: i18n.translate('xpack.ingestManager.editPackageConfig.failedNotificationTitle', { - defaultMessage: `Error updating '{packageConfigName}'`, + title: i18n.translate('xpack.ingestManager.editPackagePolicy.failedNotificationTitle', { + defaultMessage: `Error updating '{packagePolicyName}'`, values: { - packageConfigName: packageConfig.name, + packagePolicyName: packagePolicy.name, }, }), toastMessage: i18n.translate( - 'xpack.ingestManager.editPackageConfig.failedConflictNotificationMessage', + 'xpack.ingestManager.editPackagePolicy.failedConflictNotificationMessage', { - defaultMessage: `Data is out of date. Refresh the page to get the latest configuration.`, + defaultMessage: `Data is out of date. Refresh the page to get the latest policy.`, } ), }); } else { notifications.toasts.addError(error, { - title: i18n.translate('xpack.ingestManager.editPackageConfig.failedNotificationTitle', { - defaultMessage: `Error updating '{packageConfigName}'`, + title: i18n.translate('xpack.ingestManager.editPackagePolicy.failedNotificationTitle', { + defaultMessage: `Error updating '{packagePolicyName}'`, values: { - packageConfigName: packageConfig.name, + packagePolicyName: packagePolicy.name, }, }), }); @@ -274,72 +274,72 @@ export const EditPackageConfigPage: React.FunctionComponent = () => { }; const layoutProps = { - from: 'edit' as CreatePackageConfigFrom, + from: 'edit' as CreatePackagePolicyFrom, cancelUrl, - agentConfig, + agentPolicy, packageInfo, }; const configurePackage = useMemo( () => - agentConfig && packageInfo ? ( + agentPolicy && packageInfo ? ( <> - - ) : null, [ - agentConfig, + agentPolicy, formState, - packageConfig, - packageConfigId, + packagePolicy, + packagePolicyId, packageInfo, - updatePackageConfig, + updatePackagePolicy, validationResults, ] ); return ( - + {isLoadingData ? ( - ) : loadingError || !agentConfig || !packageInfo ? ( + ) : loadingError || !agentPolicy || !packageInfo ? ( } error={ loadingError || - i18n.translate('xpack.ingestManager.editPackageConfig.errorLoadingDataMessage', { + i18n.translate('xpack.ingestManager.editPackagePolicy.errorLoadingDataMessage', { defaultMessage: 'There was an error loading this intergration information', }) } /> ) : ( <> - + {formState === 'CONFIRM' && ( - setFormState('VALID')} /> @@ -358,10 +358,10 @@ export const EditPackageConfigPage: React.FunctionComponent = () => { > - {agentConfig && packageInfo && formState === 'INVALID' ? ( + {agentPolicy && packageInfo && formState === 'INVALID' ? ( ) : null} @@ -370,7 +370,7 @@ export const EditPackageConfigPage: React.FunctionComponent = () => { @@ -385,7 +385,7 @@ export const EditPackageConfigPage: React.FunctionComponent = () => { fill > @@ -396,14 +396,14 @@ export const EditPackageConfigPage: React.FunctionComponent = () => { )} - + ); }; -const Breadcrumb: React.FunctionComponent<{ configName: string; configId: string }> = ({ - configName, - configId, +const Breadcrumb: React.FunctionComponent<{ policyName: string; policyId: string }> = ({ + policyName, + policyId, }) => { - useBreadcrumbs('edit_integration', { configName, configId }); + useBreadcrumbs('edit_integration', { policyName, policyId }); return null; }; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/index.tsx new file mode 100644 index 00000000000000..ed6d1a6e4610c5 --- /dev/null +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/index.tsx @@ -0,0 +1,36 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import React from 'react'; +import { HashRouter as Router, Switch, Route } from 'react-router-dom'; +import { PAGE_ROUTING_PATHS } from '../../constants'; +import { useBreadcrumbs } from '../../hooks'; +import { AgentPolicyListPage } from './list_page'; +import { AgentPolicyDetailsPage } from './details_page'; +import { CreatePackagePolicyPage } from './create_package_policy_page'; +import { EditPackagePolicyPage } from './edit_package_policy_page'; + +export const AgentPolicyApp: React.FunctionComponent = () => { + useBreadcrumbs('policies'); + + return ( + + + + + + + + + + + + + + + + + ); +}; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/list_page/components/create_config.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/list_page/components/create_agent_policy.tsx similarity index 65% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/list_page/components/create_config.tsx rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/list_page/components/create_agent_policy.tsx index 749716b473c858..b072990727e3cc 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/list_page/components/create_config.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/list_page/components/create_agent_policy.tsx @@ -21,25 +21,25 @@ import { EuiFlyoutProps, EuiSpacer, } from '@elastic/eui'; -import { NewAgentConfig, AgentConfig } from '../../../../types'; -import { useCapabilities, useCore, sendCreateAgentConfig } from '../../../../hooks'; -import { AgentConfigForm, agentConfigFormValidation } from '../../components'; +import { NewAgentPolicy, AgentPolicy } from '../../../../types'; +import { useCapabilities, useCore, sendCreateAgentPolicy } from '../../../../hooks'; +import { AgentPolicyForm, agentPolicyFormValidation } from '../../components'; const FlyoutWithHigherZIndex = styled(EuiFlyout)` z-index: ${(props) => props.theme.eui.euiZLevel5}; `; interface Props extends EuiFlyoutProps { - onClose: (createdAgentConfig?: AgentConfig) => void; + onClose: (createdAgentPolicy?: AgentPolicy) => void; } -export const CreateAgentConfigFlyout: React.FunctionComponent = ({ +export const CreateAgentPolicyFlyout: React.FunctionComponent = ({ onClose, ...restOfProps }) => { const { notifications } = useCore(); const hasWriteCapabilites = useCapabilities().write; - const [agentConfig, setAgentConfig] = useState({ + const [agentPolicy, setAgentPolicy] = useState({ name: '', description: '', namespace: 'default', @@ -48,26 +48,26 @@ export const CreateAgentConfigFlyout: React.FunctionComponent = ({ }); const [isLoading, setIsLoading] = useState(false); const [withSysMonitoring, setWithSysMonitoring] = useState(true); - const validation = agentConfigFormValidation(agentConfig); + const validation = agentPolicyFormValidation(agentPolicy); - const updateAgentConfig = (updatedFields: Partial) => { - setAgentConfig({ - ...agentConfig, + const updateAgentPolicy = (updatedFields: Partial) => { + setAgentPolicy({ + ...agentPolicy, ...updatedFields, }); }; - const createAgentConfig = async () => { - return await sendCreateAgentConfig(agentConfig, { withSysMonitoring }); + const createAgentPolicy = async () => { + return await sendCreateAgentPolicy(agentPolicy, { withSysMonitoring }); }; const header = ( - + -

+

@@ -75,8 +75,8 @@ export const CreateAgentConfigFlyout: React.FunctionComponent = ({

@@ -85,9 +85,9 @@ export const CreateAgentConfigFlyout: React.FunctionComponent = ({ const body = ( - setWithSysMonitoring(newValue)} validation={validation} @@ -101,7 +101,7 @@ export const CreateAgentConfigFlyout: React.FunctionComponent = ({ onClose()} flush="left"> @@ -114,15 +114,15 @@ export const CreateAgentConfigFlyout: React.FunctionComponent = ({ onClick={async () => { setIsLoading(true); try { - const { data, error } = await createAgentConfig(); + const { data, error } = await createAgentPolicy(); setIsLoading(false); if (data?.success) { notifications.toasts.addSuccess( i18n.translate( - 'xpack.ingestManager.createAgentConfig.successNotificationTitle', + 'xpack.ingestManager.createAgentPolicy.successNotificationTitle', { - defaultMessage: "Agent config '{name}' created", - values: { name: agentConfig.name }, + defaultMessage: "Agent policy '{name}' created", + values: { name: agentPolicy.name }, } ) ); @@ -132,9 +132,9 @@ export const CreateAgentConfigFlyout: React.FunctionComponent = ({ error ? error.message : i18n.translate( - 'xpack.ingestManager.createAgentConfig.errorNotificationTitle', + 'xpack.ingestManager.createAgentPolicy.errorNotificationTitle', { - defaultMessage: 'Unable to create agent config', + defaultMessage: 'Unable to create agent policy', } ) ); @@ -142,16 +142,16 @@ export const CreateAgentConfigFlyout: React.FunctionComponent = ({ } catch (e) { setIsLoading(false); notifications.toasts.addDanger( - i18n.translate('xpack.ingestManager.createAgentConfig.errorNotificationTitle', { - defaultMessage: 'Unable to create agent config', + i18n.translate('xpack.ingestManager.createAgentPolicy.errorNotificationTitle', { + defaultMessage: 'Unable to create agent policy', }) ); } }} > diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/list_page/components/index.ts b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/list_page/components/index.ts similarity index 78% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/list_page/components/index.ts rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/list_page/components/index.ts index 43668b4ffb8049..de95b6748eb6c2 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/list_page/components/index.ts +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/list_page/components/index.ts @@ -3,4 +3,4 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -export { CreateAgentConfigFlyout } from './create_config'; +export { CreateAgentPolicyFlyout } from './create_agent_policy'; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/list_page/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/list_page/index.tsx similarity index 61% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/list_page/index.tsx rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/list_page/index.tsx index 229adb946412b2..361b1c33f1a042 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/list_page/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_policy/list_page/index.tsx @@ -21,12 +21,12 @@ import { CriteriaWithPagination } from '@elastic/eui/src/components/basic_table/ import { i18n } from '@kbn/i18n'; import { FormattedMessage, FormattedDate } from '@kbn/i18n/react'; import { useHistory } from 'react-router-dom'; -import { AgentConfig } from '../../../types'; -import { AGENT_CONFIG_SAVED_OBJECT_TYPE } from '../../../constants'; +import { AgentPolicy } from '../../../types'; +import { AGENT_POLICY_SAVED_OBJECT_TYPE } from '../../../constants'; import { WithHeaderLayout } from '../../../layouts'; import { useCapabilities, - useGetAgentConfigs, + useGetAgentPolicies, usePagination, useSorting, useLink, @@ -35,10 +35,10 @@ import { useBreadcrumbs, } from '../../../hooks'; import { SearchBar } from '../../../components'; -import { LinkedAgentCount, AgentConfigActionMenu } from '../components'; -import { CreateAgentConfigFlyout } from './components'; +import { LinkedAgentCount, AgentPolicyActionMenu } from '../components'; +import { CreateAgentPolicyFlyout } from './components'; -const AgentConfigListPageLayout: React.FunctionComponent = ({ children }) => ( +const AgentPolicyListPageLayout: React.FunctionComponent = ({ children }) => ( @@ -46,8 +46,8 @@ const AgentConfigListPageLayout: React.FunctionComponent = ({ children }) => (

@@ -56,8 +56,8 @@ const AgentConfigListPageLayout: React.FunctionComponent = ({ children }) => (

@@ -69,10 +69,9 @@ const AgentConfigListPageLayout: React.FunctionComponent = ({ children }) => (
); -export const AgentConfigListPage: React.FunctionComponent<{}> = () => { - useBreadcrumbs('configurations_list'); +export const AgentPolicyListPage: React.FunctionComponent<{}> = () => { + useBreadcrumbs('policies_list'); const { getHref, getPath } = useLink(); - // Config information const hasWriteCapabilites = useCapabilities().write; const { fleet: { enabled: isFleetEnabled }, @@ -86,30 +85,30 @@ export const AgentConfigListPage: React.FunctionComponent<{}> = () => { : urlParams.kuery ?? '' ); const { pagination, pageSizeOptions, setPagination } = usePagination(); - const { sorting, setSorting } = useSorting({ + const { sorting, setSorting } = useSorting({ field: 'updated_at', direction: 'desc', }); const history = useHistory(); - const isCreateAgentConfigFlyoutOpen = 'create' in urlParams; - const setIsCreateAgentConfigFlyoutOpen = useCallback( + const isCreateAgentPolicyFlyoutOpen = 'create' in urlParams; + const setIsCreateAgentPolicyFlyoutOpen = useCallback( (isOpen: boolean) => { - if (isOpen !== isCreateAgentConfigFlyoutOpen) { + if (isOpen !== isCreateAgentPolicyFlyoutOpen) { if (isOpen) { history.push( - `${getPath('configurations_list')}?${toUrlParams({ ...urlParams, create: null })}` + `${getPath('policies_list')}?${toUrlParams({ ...urlParams, create: null })}` ); } else { const { create, ...params } = urlParams; - history.push(`${getPath('configurations_list')}?${toUrlParams(params)}`); + history.push(`${getPath('policies_list')}?${toUrlParams(params)}`); } } }, - [getPath, history, isCreateAgentConfigFlyoutOpen, toUrlParams, urlParams] + [getPath, history, isCreateAgentPolicyFlyoutOpen, toUrlParams, urlParams] ); - // Fetch agent configs - const { isLoading, data: agentConfigData, sendRequest } = useGetAgentConfigs({ + // Fetch agent policies + const { isLoading, data: agentPolicyData, sendRequest } = useGetAgentPolicies({ page: pagination.currentPage, perPage: pagination.pageSize, sortField: sorting?.field, @@ -117,35 +116,35 @@ export const AgentConfigListPage: React.FunctionComponent<{}> = () => { kuery: search, }); - // Some configs retrieved, set up table props + // Some policies retrieved, set up table props const columns = useMemo(() => { const cols: Array< - EuiTableFieldDataColumnType | EuiTableActionsColumnType + EuiTableFieldDataColumnType | EuiTableActionsColumnType > = [ { field: 'name', sortable: true, - name: i18n.translate('xpack.ingestManager.agentConfigList.nameColumnTitle', { + name: i18n.translate('xpack.ingestManager.agentPolicyList.nameColumnTitle', { defaultMessage: 'Name', }), width: '20%', - render: (name: string, agentConfig: AgentConfig) => ( + render: (name: string, agentPolicy: AgentPolicy) => ( - {name || agentConfig.id} + {name || agentPolicy.id} @@ -154,7 +153,7 @@ export const AgentConfigListPage: React.FunctionComponent<{}> = () => { }, { field: 'description', - name: i18n.translate('xpack.ingestManager.agentConfigList.descriptionColumnTitle', { + name: i18n.translate('xpack.ingestManager.agentPolicyList.descriptionColumnTitle', { defaultMessage: 'Description', }), width: '35%', @@ -167,40 +166,46 @@ export const AgentConfigListPage: React.FunctionComponent<{}> = () => { { field: 'updated_at', sortable: true, - name: i18n.translate('xpack.ingestManager.agentConfigList.updatedOnColumnTitle', { + name: i18n.translate('xpack.ingestManager.agentPolicyList.updatedOnColumnTitle', { defaultMessage: 'Last updated on', }), - render: (date: AgentConfig['updated_at']) => ( + render: (date: AgentPolicy['updated_at']) => ( ), }, { field: 'agents', - name: i18n.translate('xpack.ingestManager.agentConfigList.agentsColumnTitle', { + name: i18n.translate('xpack.ingestManager.agentPolicyList.agentsColumnTitle', { defaultMessage: 'Agents', }), dataType: 'number', - render: (agents: number, config: AgentConfig) => ( - + render: (agents: number, agentPolicy: AgentPolicy) => ( + ), }, { - field: 'package_configs', - name: i18n.translate('xpack.ingestManager.agentConfigList.packageConfigsCountColumnTitle', { - defaultMessage: 'Integrations', - }), + field: 'package_policies', + name: i18n.translate( + 'xpack.ingestManager.agentPolicyList.packagePoliciesCountColumnTitle', + { + defaultMessage: 'Integrations', + } + ), dataType: 'number', - render: (packageConfigs: AgentConfig['package_configs']) => - packageConfigs ? packageConfigs.length : 0, + render: (packagePolicies: AgentPolicy['package_policies']) => + packagePolicies ? packagePolicies.length : 0, }, { - name: i18n.translate('xpack.ingestManager.agentConfigList.actionsColumnTitle', { + name: i18n.translate('xpack.ingestManager.agentPolicyList.actionsColumnTitle', { defaultMessage: 'Actions', }), actions: [ { - render: (config: AgentConfig) => ( - sendRequest()} /> + render: (agentPolicy: AgentPolicy) => ( + sendRequest()} + /> ), }, ], @@ -215,21 +220,21 @@ export const AgentConfigListPage: React.FunctionComponent<{}> = () => { return cols; }, [getHref, isFleetEnabled, sendRequest]); - const createAgentConfigButton = useMemo( + const createAgentPolicyButton = useMemo( () => ( setIsCreateAgentConfigFlyoutOpen(true)} + onClick={() => setIsCreateAgentPolicyFlyoutOpen(true)} > ), - [hasWriteCapabilites, setIsCreateAgentConfigFlyoutOpen] + [hasWriteCapabilites, setIsCreateAgentPolicyFlyoutOpen] ); const emptyPrompt = useMemo( @@ -238,18 +243,18 @@ export const AgentConfigListPage: React.FunctionComponent<{}> = () => { title={

} - actions={createAgentConfigButton} + actions={createAgentPolicyButton} /> ), - [createAgentConfigButton] + [createAgentPolicyButton] ); - const onTableChange = (criteria: CriteriaWithPagination) => { + const onTableChange = (criteria: CriteriaWithPagination) => { const newPagination = { ...pagination, currentPage: criteria.page.index + 1, @@ -260,11 +265,11 @@ export const AgentConfigListPage: React.FunctionComponent<{}> = () => { }; return ( - - {isCreateAgentConfigFlyoutOpen ? ( - + {isCreateAgentPolicyFlyoutOpen ? ( + { - setIsCreateAgentConfigFlyoutOpen(false); + setIsCreateAgentPolicyFlyoutOpen(false); sendRequest(); }} /> @@ -280,41 +285,41 @@ export const AgentConfigListPage: React.FunctionComponent<{}> = () => { }); setSearch(newSearch); }} - fieldPrefix={AGENT_CONFIG_SAVED_OBJECT_TYPE} + fieldPrefix={AGENT_POLICY_SAVED_OBJECT_TYPE} /> sendRequest()}> - {createAgentConfigButton} + {createAgentPolicyButton}
- + loading={isLoading} hasActions={true} noItemsMessage={ isLoading ? ( - ) : !search.trim() && (agentConfigData?.total ?? 0) === 0 ? ( + ) : !search.trim() && (agentPolicyData?.total ?? 0) === 0 ? ( emptyPrompt ) : ( setSearch('')}> @@ -323,19 +328,19 @@ export const AgentConfigListPage: React.FunctionComponent<{}> = () => { /> ) } - items={agentConfigData ? agentConfigData.items : []} + items={agentPolicyData ? agentPolicyData.items : []} itemId="id" columns={columns} isSelectable={false} pagination={{ pageIndex: pagination.currentPage - 1, pageSize: pagination.pageSize, - totalItemCount: agentConfigData ? agentConfigData.total : 0, + totalItemCount: agentPolicyData ? agentPolicyData.total : 0, pageSizeOptions, }} sorting={{ sort: sorting }} onChange={onTableChange} /> - + ); }; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/data_stream/list_page/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/data_stream/list_page/index.tsx index 39e6d90e64bea7..d8ab46fbf87f7f 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/data_stream/list_page/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/data_stream/list_page/index.tsx @@ -66,7 +66,7 @@ export const DataStreamListPage: React.FunctionComponent<{}> = () => { // Fetch data streams const { isLoading, data: dataStreamsData, sendRequest } = useGetDataStreams(); - // Some configs retrieved, set up table props + // Some policies retrieved, set up table props const columns = useMemo(() => { const cols: Array< EuiTableFieldDataColumnType | EuiTableActionsColumnType diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/index.tsx index f15b7d7f182a8d..b605b882bc82cd 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/index.tsx @@ -8,7 +8,7 @@ import React from 'react'; import { HashRouter as Router, Switch, Route } from 'react-router-dom'; import { PAGE_ROUTING_PATHS } from '../../constants'; import { useBreadcrumbs } from '../../hooks'; -import { CreatePackageConfigPage } from '../agent_config/create_package_config_page'; +import { CreatePackagePolicyPage } from '../agent_policy/create_package_policy_page'; import { EPMHomePage } from './screens/home'; import { Detail } from './screens/detail'; @@ -18,8 +18,8 @@ export const EPMApp: React.FunctionComponent = () => { return ( - - + + diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/confirm_package_uninstall.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/confirm_package_uninstall.tsx index 11cdbe0be7b626..f4d5226ebe950a 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/confirm_package_uninstall.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/confirm_package_uninstall.tsx @@ -56,7 +56,7 @@ export const ConfirmPackageUninstall = (props: ConfirmPackageUninstallProps) =>

diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/content.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/content.tsx index f53b4e9150ca10..0443915d8224ce 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/content.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/content.tsx @@ -13,7 +13,7 @@ import { AssetsFacetGroup } from '../../components/assets_facet_group'; import { CenterColumn, LeftColumn, RightColumn } from './layout'; import { OverviewPanel } from './overview_panel'; import { SideNavLinks } from './side_nav_links'; -import { PackageConfigsPanel } from './package_configs_panel'; +import { PackagePoliciesPanel } from './package_policies_panel'; import { SettingsPanel } from './settings_panel'; type ContentProps = PackageInfo & Pick; @@ -63,7 +63,7 @@ export function ContentPanel(props: ContentPanelProps) { /> ); case 'usages': - return ; + return ; case 'overview': default: return ; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/index.tsx index 3267fbbe3733c2..84d3f97f3ee059 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/index.tsx @@ -182,12 +182,12 @@ export function Detail() { fill isDisabled={!hasWriteCapabilites} iconType="plusInCircle" - href={getHref('add_integration_to_configuration', { + href={getHref('add_integration_to_policy', { pkgkey, })} > { +export const PackagePoliciesPanel = ({ name, version }: PackagePoliciesPanelProps) => { const { getPath } = useLink(); const getPackageInstallStatus = useGetPackageInstallStatus(); const packageInstallStatus = getPackageInstallStatus(name); diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/settings_panel.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/settings_panel.tsx index 4832a89479026e..4ac6fe6872e17e 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/settings_panel.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/epm/screens/detail/settings_panel.tsx @@ -10,8 +10,8 @@ import { EuiTitle, EuiFlexGroup, EuiFlexItem, EuiText } from '@elastic/eui'; import { EuiSpacer } from '@elastic/eui'; import styled from 'styled-components'; import { InstallStatus, PackageInfo } from '../../../../types'; -import { useGetPackageConfigs } from '../../../../hooks'; -import { PACKAGE_CONFIG_SAVED_OBJECT_TYPE } from '../../../../constants'; +import { useGetPackagePolicies } from '../../../../hooks'; +import { PACKAGE_POLICY_SAVED_OBJECT_TYPE } from '../../../../constants'; import { useGetPackageInstallStatus } from '../../hooks'; import { InstallationButton } from './installation_button'; import { UpdateIcon } from '../../components/icons'; @@ -46,13 +46,13 @@ export const SettingsPanel = ( ) => { const { name, title, removable, latestVersion, version } = props; const getPackageInstallStatus = useGetPackageInstallStatus(); - const { data: packageConfigsData } = useGetPackageConfigs({ + const { data: packagePoliciesData } = useGetPackagePolicies({ perPage: 0, page: 1, - kuery: `${PACKAGE_CONFIG_SAVED_OBJECT_TYPE}.package.name:${props.name}`, + kuery: `${PACKAGE_POLICY_SAVED_OBJECT_TYPE}.package.name:${props.name}`, }); const { status: installationStatus, version: installedVersion } = getPackageInstallStatus(name); - const packageHasUsages = !!packageConfigsData?.total; + const packageHasUsages = !!packagePoliciesData?.total; const updateAvailable = installedVersion && installedVersion < latestVersion ? true : false; const isViewingOldPackage = version < latestVersion; // hide install/remove options if the user has version of the package is installed @@ -185,7 +185,7 @@ export const SettingsPanel = (

@@ -194,7 +194,7 @@ export const SettingsPanel = (

= { overview: i18n.translate('xpack.ingestManager.epm.packageDetailsNav.overviewLinkText', { defaultMessage: 'Overview', }), - usages: i18n.translate('xpack.ingestManager.epm.packageDetailsNav.packageConfigsLinkText', { + usages: i18n.translate('xpack.ingestManager.epm.packageDetailsNav.packagePoliciesLinkText', { defaultMessage: 'Usages', }), settings: i18n.translate('xpack.ingestManager.epm.packageDetailsNav.settingsLinkText', { diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/actions_menu.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/actions_menu.tsx index 0f48a230bbf5c8..636ff7a5ff9896 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/actions_menu.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/actions_menu.tsx @@ -9,7 +9,7 @@ import { FormattedMessage } from '@kbn/i18n/react'; import { Agent } from '../../../../types'; import { useCapabilities } from '../../../../hooks'; import { ContextMenuActions } from '../../../../components'; -import { AgentUnenrollProvider, AgentReassignConfigFlyout } from '../../components'; +import { AgentUnenrollProvider, AgentReassignAgentPolicyFlyout } from '../../components'; import { useAgentRefresh } from '../hooks'; export const AgentDetailsActionMenu: React.FunctionComponent<{ @@ -34,7 +34,7 @@ export const AgentDetailsActionMenu: React.FunctionComponent<{ <> {isReassignFlyoutOpen && ( - + )} , diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/agent_details.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/agent_details.tsx index de0c65d508db9e..68abb43abac184 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/agent_details.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/agent_details.tsx @@ -13,14 +13,14 @@ import { EuiLink, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; -import { Agent, AgentConfig } from '../../../../types'; +import { Agent, AgentPolicy } from '../../../../types'; import { useLink } from '../../../../hooks'; import { AgentHealth } from '../../components'; export const AgentDetailsContent: React.FunctionComponent<{ agent: Agent; - agentConfig?: AgentConfig; -}> = memo(({ agent, agentConfig }) => { + agentPolicy?: AgentPolicy; +}> = memo(({ agent, agentPolicy }) => { const { getHref } = useLink(); return ( @@ -48,18 +48,18 @@ export const AgentDetailsContent: React.FunctionComponent<{ description: , }, { - title: i18n.translate('xpack.ingestManager.agentDetails.agentConfigurationLabel', { - defaultMessage: 'Agent configuration', + title: i18n.translate('xpack.ingestManager.agentDetails.agentPolicyLabel', { + defaultMessage: 'Agent policy', }), - description: agentConfig ? ( + description: agentPolicy ? ( - {agentConfig.name || agent.config_id} + {agentPolicy.name || agent.policy_id} ) : ( - agent.config_id || '-' + agent.policy_id || '-' ), }, { diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/type_labels.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/type_labels.tsx index 43e4d696ded660..56af9519bc1dac 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/type_labels.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/components/type_labels.tsx @@ -66,8 +66,8 @@ export const SUBTYPE_LABEL: { [key in AgentEvent['subtype']]: JSX.Element } = { CONFIG: ( ), diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/index.tsx index 0bd25ac8cf4015..219b343eba41b5 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/index.tsx @@ -19,12 +19,12 @@ import { import { Props as EuiTabProps } from '@elastic/eui/src/components/tabs/tab'; import { FormattedMessage } from '@kbn/i18n/react'; import { i18n } from '@kbn/i18n'; -import { Agent, AgentConfig, AgentDetailsReassignConfigAction } from '../../../types'; +import { Agent, AgentPolicy, AgentDetailsReassignPolicyAction } from '../../../types'; import { PAGE_ROUTING_PATHS } from '../../../constants'; import { Loading, Error } from '../../../components'; import { useGetOneAgent, - useGetOneAgentConfig, + useGetOneAgentPolicy, useLink, useBreadcrumbs, useCore, @@ -56,15 +56,15 @@ export const AgentDetailsPage: React.FunctionComponent = () => { pollIntervalMs: 5000, }); const { - isLoading: isAgentConfigLoading, - data: agentConfigData, - sendRequest: sendAgentConfigRequest, - } = useGetOneAgentConfig(agentData?.item?.config_id); + isLoading: isAgentPolicyLoading, + data: agentPolicyData, + sendRequest: sendAgentPolicyRequest, + } = useGetOneAgentPolicy(agentData?.item?.policy_id); const { application: { navigateToApp }, } = useCore(); - const routeState = useIntraAppState(); + const routeState = useIntraAppState(); const queryParams = new URLSearchParams(useLocation().search); const openReassignFlyoutOpenByDefault = queryParams.get('openReassignFlyout') === 'true'; @@ -127,20 +127,20 @@ export const AgentDetailsPage: React.FunctionComponent = () => { }, { isDivider: true }, { - label: i18n.translate('xpack.ingestManager.agentDetails.configurationLabel', { - defaultMessage: 'Configuration', + label: i18n.translate('xpack.ingestManager.agentDetails.policyLabel', { + defaultMessage: 'Policy', }), - content: isAgentConfigLoading ? ( + content: isAgentPolicyLoading ? ( - ) : agentConfigData?.item ? ( + ) : agentPolicyData?.item ? ( - {agentConfigData.item.name || agentData.item.config_id} + {agentPolicyData.item.name || agentData.item.policy_id} ) : ( - agentData.item.config_id || '-' + agentData.item.policy_id || '-' ), }, { isDivider: true }, @@ -174,7 +174,7 @@ export const AgentDetailsPage: React.FunctionComponent = () => { ) : undefined, /* eslint-disable-next-line react-hooks/exhaustive-deps */ - [agentConfigData, agentData, getHref, isAgentConfigLoading] + [agentPolicyData, agentData, getHref, isAgentPolicyLoading] ); const headerTabs = useMemo(() => { @@ -203,7 +203,7 @@ export const AgentDetailsPage: React.FunctionComponent = () => { value={{ refresh: () => { sendAgentRequest(); - sendAgentConfigRequest(); + sendAgentPolicyRequest(); }, }} > @@ -225,7 +225,7 @@ export const AgentDetailsPage: React.FunctionComponent = () => { error={error} /> ) : agentData && agentData.item ? ( - + ) : ( { const AgentDetailsPageContent: React.FunctionComponent<{ agent: Agent; - agentConfig?: AgentConfig; -}> = ({ agent, agentConfig }) => { + agentPolicy?: AgentPolicy; +}> = ({ agent, agentPolicy }) => { useBreadcrumbs('fleet_agent_details', { agentHost: typeof agent.local_metadata.host === 'object' && @@ -266,7 +266,7 @@ const AgentDetailsPageContent: React.FunctionComponent<{ { - return ; + return ; }} /> void; refre void; refre onReassignClick(); }} disabled={!agent.active} - key="reassignConfig" + key="reassignPolicy" > , @@ -150,9 +150,9 @@ export const AgentListPage: React.FunctionComponent<{}> = () => { const [search, setSearch] = useState(defaultKuery); const { pagination, pageSizeOptions, setPagination } = usePagination(); - // Configs state for filtering - const [isConfigsFilterOpen, setIsConfigsFilterOpen] = useState(false); - const [selectedConfigs, setSelectedConfigs] = useState([]); + // Policies state for filtering + const [isAgentPoliciesFilterOpen, setIsAgentPoliciesFilterOpen] = useState(false); + const [selectedAgentPolicies, setSelectedAgentPolicies] = useState([]); // Status for filtering const [isStatusFilterOpen, setIsStatutsFilterOpen] = useState(false); @@ -160,18 +160,20 @@ export const AgentListPage: React.FunctionComponent<{}> = () => { const clearFilters = useCallback(() => { setSearch(''); - setSelectedConfigs([]); + setSelectedAgentPolicies([]); setSelectedStatus([]); - }, [setSearch, setSelectedConfigs, setSelectedStatus]); + }, [setSearch, setSelectedAgentPolicies, setSelectedStatus]); - // Add a config id to current search - const addConfigFilter = (configId: string) => { - setSelectedConfigs([...selectedConfigs, configId]); + // Add a agent policy id to current search + const addAgentPolicyFilter = (policyId: string) => { + setSelectedAgentPolicies([...selectedAgentPolicies, policyId]); }; - // Remove a config id from current search - const removeConfigFilter = (configId: string) => { - setSelectedConfigs(selectedConfigs.filter((config) => config !== configId)); + // Remove a agent policy id from current search + const removeAgentPolicyFilter = (policyId: string) => { + setSelectedAgentPolicies( + selectedAgentPolicies.filter((agentPolicy) => agentPolicy !== policyId) + ); }; // Agent enrollment flyout state @@ -181,12 +183,12 @@ export const AgentListPage: React.FunctionComponent<{}> = () => { const [agentToReassignId, setAgentToReassignId] = useState(undefined); let kuery = search.trim(); - if (selectedConfigs.length) { + if (selectedAgentPolicies.length) { if (kuery) { kuery = `(${kuery}) and`; } - kuery = `${kuery} ${AGENT_SAVED_OBJECT_TYPE}.config_id : (${selectedConfigs - .map((config) => `"${config}"`) + kuery = `${kuery} ${AGENT_SAVED_OBJECT_TYPE}.policy_id : (${selectedAgentPolicies + .map((agentPolicy) => `"${agentPolicy}"`) .join(' or ')})`; } @@ -229,20 +231,20 @@ export const AgentListPage: React.FunctionComponent<{}> = () => { const totalAgents = agentsRequest.data ? agentsRequest.data.total : 0; const { isLoading } = agentsRequest; - const agentConfigsRequest = useGetAgentConfigs({ + const agentPoliciesRequest = useGetAgentPolicies({ page: 1, perPage: 1000, }); - const agentConfigs = agentConfigsRequest.data ? agentConfigsRequest.data.items : []; - const agentConfigsIndexedById = useMemo(() => { - return agentConfigs.reduce((acc, config) => { - acc[config.id] = config; + const agentPolicies = agentPoliciesRequest.data ? agentPoliciesRequest.data.items : []; + const agentPoliciesIndexedById = useMemo(() => { + return agentPolicies.reduce((acc, agentPolicy) => { + acc[agentPolicy.id] = agentPolicy; return acc; - }, {} as { [k: string]: AgentConfig }); - }, [agentConfigs]); - const { isLoading: isAgentConfigsLoading } = agentConfigsRequest; + }, {} as { [k: string]: AgentPolicy }); + }, [agentPolicies]); + const { isLoading: isAgentPoliciesLoading } = agentPoliciesRequest; const columns = [ { @@ -265,38 +267,38 @@ export const AgentListPage: React.FunctionComponent<{}> = () => { render: (active: boolean, agent: any) => , }, { - field: 'config_id', - name: i18n.translate('xpack.ingestManager.agentList.configColumnTitle', { - defaultMessage: 'Agent config', + field: 'policy_id', + name: i18n.translate('xpack.ingestManager.agentList.policyColumnTitle', { + defaultMessage: 'Agent policy', }), - render: (configId: string, agent: Agent) => { - const configName = agentConfigs.find((p) => p.id === configId)?.name; + render: (policyId: string, agent: Agent) => { + const policyName = agentPolicies.find((p) => p.id === policyId)?.name; return ( - {configName || configId} + {policyName || policyId} - {agent.config_revision && ( + {agent.policy_revision && ( )} - {agent.config_id && - agent.config_revision && - agentConfigsIndexedById[agent.config_id] && - agentConfigsIndexedById[agent.config_id].revision > agent.config_revision && ( + {agent.policy_id && + agent.policy_revision && + agentPoliciesIndexedById[agent.policy_id] && + agentPoliciesIndexedById[agent.policy_id].revision > agent.policy_revision && ( @@ -382,13 +384,13 @@ export const AgentListPage: React.FunctionComponent<{}> = () => { <> {isEnrollmentFlyoutOpen ? ( setIsEnrollmentFlyoutOpen(false)} /> ) : null} {agentToReassign && ( - { setAgentToReassignId(undefined); @@ -424,7 +426,7 @@ export const AgentListPage: React.FunctionComponent<{}> = () => { isSelected={isStatusFilterOpen} hasActiveFilters={selectedStatus.length > 0} numActiveFilters={selectedStatus.length} - disabled={isAgentConfigsLoading} + disabled={isAgentPoliciesLoading} > = () => { button={ setIsConfigsFilterOpen(!isConfigsFilterOpen)} - isSelected={isConfigsFilterOpen} - hasActiveFilters={selectedConfigs.length > 0} - numActiveFilters={selectedConfigs.length} - numFilters={agentConfigs.length} - disabled={isAgentConfigsLoading} + onClick={() => setIsAgentPoliciesFilterOpen(!isAgentPoliciesFilterOpen)} + isSelected={isAgentPoliciesFilterOpen} + hasActiveFilters={selectedAgentPolicies.length > 0} + numActiveFilters={selectedAgentPolicies.length} + numFilters={agentPolicies.length} + disabled={isAgentPoliciesLoading} > } - isOpen={isConfigsFilterOpen} - closePopover={() => setIsConfigsFilterOpen(false)} + isOpen={isAgentPoliciesFilterOpen} + closePopover={() => setIsAgentPoliciesFilterOpen(false)} panelPaddingSize="none" >

- {agentConfigs.map((config, index) => ( + {agentPolicies.map((agentPolicy, index) => ( { - if (selectedConfigs.includes(config.id)) { - removeConfigFilter(config.id); + if (selectedAgentPolicies.includes(agentPolicy.id)) { + removeAgentPolicyFilter(agentPolicy.id); } else { - addConfigFilter(config.id); + addAgentPolicyFilter(agentPolicy.id); } }} > - {config.name} + {agentPolicy.name} ))}
@@ -521,7 +523,7 @@ export const AgentListPage: React.FunctionComponent<{}> = () => { id="xpack.ingestManager.agentList.loadingAgentsMessage" defaultMessage="Loading agents…" /> - ) : search.trim() || selectedConfigs.length || selectedStatus.length ? ( + ) : search.trim() || selectedAgentPolicies.length || selectedStatus.length ? ( void; + agentPolicies?: AgentPolicy[]; + onAgentPolicyChange?: (key: string) => void; } & ( | { withKeySelection: true; @@ -25,9 +25,9 @@ type Props = { } ); -export const EnrollmentStepAgentConfig: React.FC = (props) => { +export const EnrollmentStepAgentPolicy: React.FC = (props) => { const { notifications } = useCore(); - const { withKeySelection, agentConfigs, onConfigChange } = props; + const { withKeySelection, agentPolicies, onAgentPolicyChange } = props; const onKeyChange = props.withKeySelection && props.onKeyChange; const [isAuthenticationSettingsOpen, setIsAuthenticationSettingsOpen] = useState(false); @@ -35,17 +35,17 @@ export const EnrollmentStepAgentConfig: React.FC = (props) => { [] ); const [selectedState, setSelectedState] = useState<{ - agentConfigId?: string; + agentPolicyId?: string; enrollmentAPIKeyId?: string; }>({}); useEffect( - function triggerOnConfigChangeEffect() { - if (onConfigChange && selectedState.agentConfigId) { - onConfigChange(selectedState.agentConfigId); + function triggerOnAgentPolicyChangeEffect() { + if (onAgentPolicyChange && selectedState.agentPolicyId) { + onAgentPolicyChange(selectedState.agentPolicyId); } }, - [selectedState.agentConfigId, onConfigChange] + [selectedState.agentPolicyId, onAgentPolicyChange] ); useEffect( @@ -62,34 +62,34 @@ export const EnrollmentStepAgentConfig: React.FC = (props) => { ); useEffect( - function useDefaultConfigEffect() { - if (agentConfigs && agentConfigs.length && !selectedState.agentConfigId) { - if (agentConfigs.length === 1) { + function useDefaultAgentPolicyEffect() { + if (agentPolicies && agentPolicies.length && !selectedState.agentPolicyId) { + if (agentPolicies.length === 1) { setSelectedState({ ...selectedState, - agentConfigId: agentConfigs[0].id, + agentPolicyId: agentPolicies[0].id, }); return; } - const defaultConfig = agentConfigs.find((config) => config.is_default); - if (defaultConfig) { + const defaultAgentPolicy = agentPolicies.find((agentPolicy) => agentPolicy.is_default); + if (defaultAgentPolicy) { setSelectedState({ ...selectedState, - agentConfigId: defaultConfig.id, + agentPolicyId: defaultAgentPolicy.id, }); } } }, - [agentConfigs, selectedState] + [agentPolicies, selectedState] ); useEffect( - function useEnrollmentKeysForConfigEffect() { + function useEnrollmentKeysForAgentPolicyEffect() { if (!withKeySelection) { return; } - if (!selectedState.agentConfigId) { + if (!selectedState.agentPolicyId) { setEnrollmentAPIKeys([]); return; } @@ -109,7 +109,7 @@ export const EnrollmentStepAgentConfig: React.FC = (props) => { } setEnrollmentAPIKeys( - res.data.list.filter((key) => key.config_id === selectedState.agentConfigId) + res.data.list.filter((key) => key.policy_id === selectedState.agentPolicyId) ); } catch (error) { notifications.toasts.addError(error, { @@ -119,22 +119,22 @@ export const EnrollmentStepAgentConfig: React.FC = (props) => { } fetchEnrollmentAPIKeys(); }, - [withKeySelection, selectedState.agentConfigId, notifications.toasts] + [withKeySelection, selectedState.agentPolicyId, notifications.toasts] ); useEffect( - function useDefaultEnrollmentKeyForConfigEffect() { + function useDefaultEnrollmentKeyForAgentPolicyEffect() { if (!withKeySelection) { return; } if ( !selectedState.enrollmentAPIKeyId && enrollmentAPIKeys.length > 0 && - enrollmentAPIKeys[0].config_id === selectedState.agentConfigId + enrollmentAPIKeys[0].policy_id === selectedState.agentPolicyId ) { const enrollmentAPIKeyId = enrollmentAPIKeys[0].id; setSelectedState({ - agentConfigId: selectedState.agentConfigId, + agentPolicyId: selectedState.agentPolicyId, enrollmentAPIKeyId, }); } @@ -143,7 +143,7 @@ export const EnrollmentStepAgentConfig: React.FC = (props) => { withKeySelection, enrollmentAPIKeys, selectedState.enrollmentAPIKeyId, - selectedState.agentConfigId, + selectedState.agentPolicyId, ] ); @@ -154,31 +154,31 @@ export const EnrollmentStepAgentConfig: React.FC = (props) => { prepend={ } - isLoading={!agentConfigs} - options={(agentConfigs || []).map((config) => ({ - value: config.id, - text: config.name, + isLoading={!agentPolicies} + options={(agentPolicies || []).map((agentPolicy) => ({ + value: agentPolicy.id, + text: agentPolicy.name, }))} - value={selectedState.agentConfigId || undefined} + value={selectedState.agentPolicyId || undefined} onChange={(e) => setSelectedState({ - agentConfigId: e.target.value, + agentPolicyId: e.target.value, enrollmentAPIKeyId: undefined, }) } aria-label={i18n.translate( - 'xpack.ingestManager.enrollmentStepAgentConfig.configSelectAriaLabel', - { defaultMessage: 'Agent configuration' } + 'xpack.ingestManager.enrollmentStepAgentPolicy.policySelectAriaLabel', + { defaultMessage: 'Agent policy' } )} /> - {selectedState.agentConfigId && ( - + {selectedState.agentPolicyId && ( + )} {withKeySelection && onKeyChange && ( <> @@ -189,7 +189,7 @@ export const EnrollmentStepAgentConfig: React.FC = (props) => { onClick={() => setIsAuthenticationSettingsOpen(!isAuthenticationSettingsOpen)} > @@ -206,7 +206,7 @@ export const EnrollmentStepAgentConfig: React.FC = (props) => { prepend={ diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/index.tsx index 9c7bea51f46eaf..f85d0bea74f22f 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/index.tsx @@ -18,18 +18,18 @@ import { EuiTabs, } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; -import { AgentConfig } from '../../../../types'; +import { AgentPolicy } from '../../../../types'; import { ManagedInstructions } from './managed_instructions'; import { StandaloneInstructions } from './standalone_instructions'; interface Props { onClose: () => void; - agentConfigs?: AgentConfig[]; + agentPolicies?: AgentPolicy[]; } export const AgentEnrollmentFlyout: React.FunctionComponent = ({ onClose, - agentConfigs, + agentPolicies, }) => { const [mode, setMode] = useState<'managed' | 'standalone'>('managed'); @@ -62,9 +62,9 @@ export const AgentEnrollmentFlyout: React.FunctionComponent = ({ {mode === 'managed' ? ( - + ) : ( - + )} diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/managed_instructions.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/managed_instructions.tsx index eefb7f1bb7b5ff..3821d8a2384cad 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/managed_instructions.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/managed_instructions.tsx @@ -9,7 +9,7 @@ import { EuiSteps, EuiLink, EuiText, EuiSpacer } from '@elastic/eui'; import { EuiContainedStepProps } from '@elastic/eui/src/components/steps/steps'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; -import { AgentConfig } from '../../../../types'; +import { AgentPolicy } from '../../../../types'; import { useGetOneEnrollmentAPIKey, useCore, @@ -18,13 +18,13 @@ import { useFleetStatus, } from '../../../../hooks'; import { ManualInstructions } from '../../../../components/enrollment_instructions'; -import { DownloadStep, AgentConfigSelectionStep } from './steps'; +import { DownloadStep, AgentPolicySelectionStep } from './steps'; interface Props { - agentConfigs?: AgentConfig[]; + agentPolicies?: AgentPolicy[]; } -export const ManagedInstructions: React.FunctionComponent = ({ agentConfigs }) => { +export const ManagedInstructions: React.FunctionComponent = ({ agentPolicies }) => { const { getHref } = useLink(); const core = useCore(); const fleetStatus = useFleetStatus(); @@ -40,7 +40,7 @@ export const ManagedInstructions: React.FunctionComponent = ({ agentConfi const steps: EuiContainedStepProps[] = [ DownloadStep(), - AgentConfigSelectionStep({ agentConfigs, setSelectedAPIKeyId }), + AgentPolicySelectionStep({ agentPolicies, setSelectedAPIKeyId }), { title: i18n.translate('xpack.ingestManager.agentEnrollment.stepEnrollAndRunAgentTitle', { defaultMessage: 'Enroll and start the Elastic Agent', diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/standalone_instructions.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/standalone_instructions.tsx index bb3b2d1797ca93..c2da0b704eaff7 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/standalone_instructions.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/standalone_instructions.tsx @@ -19,59 +19,59 @@ import { import { EuiContainedStepProps } from '@elastic/eui/src/components/steps/steps'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; -import { AgentConfig } from '../../../../types'; -import { useCore, sendGetOneAgentConfigFull } from '../../../../hooks'; -import { DownloadStep, AgentConfigSelectionStep } from './steps'; -import { configToYaml, agentConfigRouteService } from '../../../../services'; +import { AgentPolicy } from '../../../../types'; +import { useCore, sendGetOneAgentPolicyFull } from '../../../../hooks'; +import { DownloadStep, AgentPolicySelectionStep } from './steps'; +import { fullAgentPolicyToYaml, agentPolicyRouteService } from '../../../../services'; interface Props { - agentConfigs?: AgentConfig[]; + agentPolicies?: AgentPolicy[]; } const RUN_INSTRUCTIONS = './elastic-agent run'; -export const StandaloneInstructions: React.FunctionComponent = ({ agentConfigs }) => { +export const StandaloneInstructions: React.FunctionComponent = ({ agentPolicies }) => { const core = useCore(); const { notifications } = core; - const [selectedConfigId, setSelectedConfigId] = useState(); - const [fullAgentConfig, setFullAgentConfig] = useState(); + const [selectedPolicyId, setSelectedPolicyId] = useState(); + const [fullAgentPolicy, setFullAgentPolicy] = useState(); - const downloadLink = selectedConfigId + const downloadLink = selectedPolicyId ? core.http.basePath.prepend( - `${agentConfigRouteService.getInfoFullDownloadPath(selectedConfigId)}?standalone=true` + `${agentPolicyRouteService.getInfoFullDownloadPath(selectedPolicyId)}?standalone=true` ) : undefined; useEffect(() => { - async function fetchFullConfig() { + async function fetchFullPolicy() { try { - if (!selectedConfigId) { + if (!selectedPolicyId) { return; } - const res = await sendGetOneAgentConfigFull(selectedConfigId, { standalone: true }); + const res = await sendGetOneAgentPolicyFull(selectedPolicyId, { standalone: true }); if (res.error) { throw res.error; } if (!res.data) { - throw new Error('No data while fetching full agent config'); + throw new Error('No data while fetching full agent policy'); } - setFullAgentConfig(res.data.item); + setFullAgentPolicy(res.data.item); } catch (error) { notifications.toasts.addError(error, { title: 'Error', }); } } - fetchFullConfig(); - }, [selectedConfigId, notifications.toasts]); + fetchFullPolicy(); + }, [selectedPolicyId, notifications.toasts]); - const yaml = useMemo(() => configToYaml(fullAgentConfig), [fullAgentConfig]); + const yaml = useMemo(() => fullAgentPolicyToYaml(fullAgentPolicy), [fullAgentPolicy]); const steps: EuiContainedStepProps[] = [ DownloadStep(), - AgentConfigSelectionStep({ agentConfigs, setSelectedConfigId }), + AgentPolicySelectionStep({ agentPolicies, setSelectedPolicyId }), { title: i18n.translate('xpack.ingestManager.agentEnrollment.stepConfigureAgentTitle', { defaultMessage: 'Configure the agent', @@ -81,7 +81,7 @@ export const StandaloneInstructions: React.FunctionComponent = ({ agentCo elastic-agent.yml, ESUsernameVariable: ES_USERNAME, @@ -96,7 +96,7 @@ export const StandaloneInstructions: React.FunctionComponent = ({ agentCo {(copy) => ( @@ -106,8 +106,8 @@ export const StandaloneInstructions: React.FunctionComponent = ({ agentCo @@ -170,7 +170,7 @@ export const StandaloneInstructions: React.FunctionComponent = ({ agentCo diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/steps.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/steps.tsx index d01e2071699209..a70741d1df7f79 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/steps.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/steps.tsx @@ -8,8 +8,8 @@ import React from 'react'; import { EuiText, EuiButton, EuiSpacer } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; import { i18n } from '@kbn/i18n'; -import { EnrollmentStepAgentConfig } from './config_selection'; -import { AgentConfig } from '../../../../types'; +import { EnrollmentStepAgentPolicy } from './agent_policy_selection'; +import { AgentPolicy } from '../../../../types'; export const DownloadStep = () => { return { @@ -41,25 +41,25 @@ export const DownloadStep = () => { }; }; -export const AgentConfigSelectionStep = ({ - agentConfigs, +export const AgentPolicySelectionStep = ({ + agentPolicies, setSelectedAPIKeyId, - setSelectedConfigId, + setSelectedPolicyId, }: { - agentConfigs?: AgentConfig[]; + agentPolicies?: AgentPolicy[]; setSelectedAPIKeyId?: (key: string) => void; - setSelectedConfigId?: (configId: string) => void; + setSelectedPolicyId?: (policyId: string) => void; }) => { return { - title: i18n.translate('xpack.ingestManager.agentEnrollment.stepChooseAgentConfigTitle', { - defaultMessage: 'Choose an agent configuration', + title: i18n.translate('xpack.ingestManager.agentEnrollment.stepChooseAgentPolicyTitle', { + defaultMessage: 'Choose an agent policy', }), children: ( - ), }; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_config_package_badges.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_policy_package_badges.tsx similarity index 52% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_config_package_badges.tsx rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_policy_package_badges.tsx index fcdb5ff02e7a41..0a3d6d54da8340 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_config_package_badges.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_policy_package_badges.tsx @@ -6,36 +6,36 @@ import React from 'react'; import { FormattedMessage } from '@kbn/i18n/react'; import { EuiSpacer, EuiText, EuiFlexGroup, EuiFlexItem, EuiBadge } from '@elastic/eui'; -import { PackageConfig } from '../../../types'; -import { useGetOneAgentConfig } from '../../../hooks'; +import { PackagePolicy } from '../../../types'; +import { useGetOneAgentPolicy } from '../../../hooks'; import { PackageIcon } from '../../../components/package_icon'; interface Props { - agentConfigId: string; + agentPolicyId: string; } -export const AgentConfigPackageBadges: React.FunctionComponent = ({ agentConfigId }) => { - const agentConfigRequest = useGetOneAgentConfig(agentConfigId); - const agentConfig = agentConfigRequest.data ? agentConfigRequest.data.item : null; +export const AgentPolicyPackageBadges: React.FunctionComponent = ({ agentPolicyId }) => { + const agentPolicyRequest = useGetOneAgentPolicy(agentPolicyId); + const agentPolicy = agentPolicyRequest.data ? agentPolicyRequest.data.item : null; - if (!agentConfig) { + if (!agentPolicy) { return null; } return ( <> {agentConfig.package_configs.length}, + count: agentPolicy.package_policies.length, + countValue: {agentPolicy.package_policies.length}, }} /> - {(agentConfig.package_configs as PackageConfig[]).map((packageConfig, idx) => { - if (!packageConfig.package) { + {(agentPolicy.package_policies as PackagePolicy[]).map((packagePolicy, idx) => { + if (!packagePolicy.package) { return null; } return ( @@ -43,13 +43,13 @@ export const AgentConfigPackageBadges: React.FunctionComponent = ({ agent - {packageConfig.package.title} + {packagePolicy.package.title} ); diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_reassign_config_flyout/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_reassign_policy_flyout/index.tsx similarity index 63% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_reassign_config_flyout/index.tsx rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_reassign_policy_flyout/index.tsx index c067de1cfea5a8..0c154bf1074c07 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_reassign_config_flyout/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_reassign_policy_flyout/index.tsx @@ -22,45 +22,48 @@ import { } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; import { Agent } from '../../../../types'; -import { sendPutAgentReassign, useCore, useGetAgentConfigs } from '../../../../hooks'; -import { AgentConfigPackageBadges } from '../agent_config_package_badges'; +import { sendPutAgentReassign, useCore, useGetAgentPolicies } from '../../../../hooks'; +import { AgentPolicyPackageBadges } from '../agent_policy_package_badges'; interface Props { onClose: () => void; agent: Agent; } -export const AgentReassignConfigFlyout: React.FunctionComponent = ({ onClose, agent }) => { +export const AgentReassignAgentPolicyFlyout: React.FunctionComponent = ({ + onClose, + agent, +}) => { const { notifications } = useCore(); - const [selectedAgentConfigId, setSelectedAgentConfigId] = useState( - agent.config_id + const [selectedAgentPolicyId, setSelectedAgentPolicyId] = useState( + agent.policy_id ); - const agentConfigsRequest = useGetAgentConfigs({ + const agentPoliciesRequest = useGetAgentPolicies({ page: 1, perPage: 1000, }); - const agentConfigs = agentConfigsRequest.data ? agentConfigsRequest.data.items : []; + const agentPolicies = agentPoliciesRequest.data ? agentPoliciesRequest.data.items : []; const [isSubmitting, setIsSubmitting] = useState(false); async function onSubmit() { try { setIsSubmitting(true); - if (!selectedAgentConfigId) { - throw new Error('No selected config id'); + if (!selectedAgentPolicyId) { + throw new Error('No selected agent policy id'); } const res = await sendPutAgentReassign(agent.id, { - config_id: selectedAgentConfigId, + policy_id: selectedAgentPolicyId, }); if (res.error) { throw res.error; } setIsSubmitting(false); const successMessage = i18n.translate( - 'xpack.ingestManager.agentReassignConfig.successSingleNotificationTitle', + 'xpack.ingestManager.agentReassignPolicy.successSingleNotificationTitle', { - defaultMessage: 'Agent configuration reassigned', + defaultMessage: 'Agent policy reassigned', } ); notifications.toasts.addSuccess(successMessage); @@ -68,7 +71,7 @@ export const AgentReassignConfigFlyout: React.FunctionComponent = ({ onCl } catch (error) { setIsSubmitting(false); notifications.toasts.addError(error, { - title: 'Unable to reassign agent configuration', + title: 'Unable to reassign agent policy', }); } } @@ -79,16 +82,16 @@ export const AgentReassignConfigFlyout: React.FunctionComponent = ({ onCl

@@ -97,26 +100,26 @@ export const AgentReassignConfigFlyout: React.FunctionComponent = ({ onCl ({ - value: config.id, - text: config.name, + options={agentPolicies.map((agentPolicy) => ({ + value: agentPolicy.id, + text: agentPolicy.name, }))} - value={selectedAgentConfigId} - onChange={(e) => setSelectedAgentConfigId(e.target.value)} + value={selectedAgentPolicyId} + onChange={(e) => setSelectedAgentPolicyId(e.target.value)} /> - {selectedAgentConfigId && ( - + {selectedAgentPolicyId && ( + )} @@ -124,21 +127,21 @@ export const AgentReassignConfigFlyout: React.FunctionComponent = ({ onCl diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/index.tsx index 8dd329806ac5ca..527f920f243659 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/index.tsx @@ -5,7 +5,7 @@ */ export * from './loading'; -export * from './agent_reassign_config_flyout'; +export * from './agent_reassign_policy_flyout'; export * from './agent_enrollment_flyout'; export * from './agent_health'; export * from './agent_unenroll_provider'; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/list_layout.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/list_layout.tsx index 16acda9dc4afd2..b01dbbd57c16fd 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/list_layout.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/list_layout.tsx @@ -21,8 +21,8 @@ import { Props as EuiTabProps } from '@elastic/eui/src/components/tabs/tab'; import { useRouteMatch } from 'react-router-dom'; import { PAGE_ROUTING_PATHS } from '../../../constants'; import { WithHeaderLayout } from '../../../layouts'; -import { useCapabilities, useLink, useGetAgentConfigs } from '../../../hooks'; -import { useGetAgentStatus } from '../../agent_config/details_page/hooks'; +import { useCapabilities, useLink, useGetAgentPolicies } from '../../../hooks'; +import { useGetAgentStatus } from '../../agent_policy/details_page/hooks'; import { AgentEnrollmentFlyout } from '../components'; import { DonutChart } from './donut_chart'; @@ -135,7 +135,7 @@ export const ListLayout: React.FunctionComponent<{}> = ({ children }) => {

@@ -143,12 +143,12 @@ export const ListLayout: React.FunctionComponent<{}> = ({ children }) => { ); - const agentConfigsRequest = useGetAgentConfigs({ + const agentPoliciesRequest = useGetAgentPolicies({ page: 1, perPage: 1000, }); - const agentConfigs = agentConfigsRequest.data ? agentConfigsRequest.data.items : []; + const agentPolicies = agentPoliciesRequest.data ? agentPoliciesRequest.data.items : []; const routeMatch = useRouteMatch(); @@ -183,7 +183,7 @@ export const ListLayout: React.FunctionComponent<{}> = ({ children }) => { > {isEnrollmentFlyoutOpen ? ( setIsEnrollmentFlyoutOpen(false)} /> ) : null} diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/enrollment_token_list_page/components/new_enrollment_key_flyout.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/enrollment_token_list_page/components/new_enrollment_key_flyout.tsx index f191b6889a60ae..8921b690690fb0 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/enrollment_token_list_page/components/new_enrollment_key_flyout.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/enrollment_token_list_page/components/new_enrollment_key_flyout.tsx @@ -21,18 +21,18 @@ import { EuiSelect, } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; -import { AgentConfig } from '../../../../types'; +import { AgentPolicy } from '../../../../types'; import { useInput, useCore, sendRequest } from '../../../../hooks'; import { enrollmentAPIKeyRouteService } from '../../../../services'; function useCreateApiKeyForm( - configDefaultValue: string | undefined, + policyIdDefaultValue: string | undefined, onSuccess: (keyId: string) => void ) { const { notifications } = useCore(); const [isLoading, setIsLoading] = useState(false); const apiKeyNameInput = useInput(''); - const configIdInput = useInput(configDefaultValue); + const policyIdInput = useInput(policyIdDefaultValue); const onSubmit = async (event: React.FormEvent) => { event.preventDefault(); @@ -43,10 +43,10 @@ function useCreateApiKeyForm( path: enrollmentAPIKeyRouteService.getCreatePath(), body: JSON.stringify({ name: apiKeyNameInput.value, - config_id: configIdInput.value, + policy_id: policyIdInput.value, }), }); - configIdInput.clear(); + policyIdInput.clear(); apiKeyNameInput.clear(); setIsLoading(false); onSuccess(res.data.item.id); @@ -66,22 +66,22 @@ function useCreateApiKeyForm( return { isLoading, onSubmit, - configIdInput, + policyIdInput, apiKeyNameInput, }; } interface Props { onClose: () => void; - agentConfigs: AgentConfig[]; + agentPolicies: AgentPolicy[]; } export const NewEnrollmentTokenFlyout: React.FunctionComponent = ({ onClose, - agentConfigs = [], + agentPolicies = [], }) => { - const configDefaultValue = agentConfigs.find((config) => config.is_default)?.id; - const form = useCreateApiKeyForm(configDefaultValue, () => { + const policyIdDefaultValue = agentPolicies.find((agentPolicy) => agentPolicy.is_default)?.id; + const form = useCreateApiKeyForm(policyIdDefaultValue, () => { onClose(); }); @@ -102,15 +102,18 @@ export const NewEnrollmentTokenFlyout: React.FunctionComponent = ({ ({ value: config.id, text: config.name }))} + defaultValue={policyIdDefaultValue} + {...form.policyIdInput.props} + options={agentPolicies.map((agentPolicy) => ({ + value: agentPolicy.id, + text: agentPolicy.name, + }))} /> diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/enrollment_token_list_page/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/enrollment_token_list_page/index.tsx index 6e8796135214ec..b3a4938b223109 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/enrollment_token_list_page/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/enrollment_token_list_page/index.tsx @@ -24,7 +24,7 @@ import { useBreadcrumbs, usePagination, useGetEnrollmentAPIKeys, - useGetAgentConfigs, + useGetAgentPolicies, sendGetOneEnrollmentAPIKey, useCore, sendDeleteOneEnrollmentAPIKey, @@ -165,12 +165,12 @@ export const EnrollmentTokenListPage: React.FunctionComponent<{}> = () => { perPage: pagination.pageSize, kuery: search.trim() !== '' ? search : undefined, }); - const agentConfigsRequest = useGetAgentConfigs({ + const agentPoliciesRequest = useGetAgentPolicies({ page: 1, perPage: 1000, }); - const agentConfigs = agentConfigsRequest.data ? agentConfigsRequest.data.items : []; + const agentPolicies = agentPoliciesRequest.data ? agentPoliciesRequest.data.items : []; const total = enrollmentAPIKeysRequest?.data?.total ?? 0; const items = enrollmentAPIKeysRequest?.data?.list ?? []; @@ -198,13 +198,13 @@ export const EnrollmentTokenListPage: React.FunctionComponent<{}> = () => { }, }, { - field: 'config_id', - name: i18n.translate('xpack.ingestManager.enrollmentTokensList.configTitle', { - defaultMessage: 'Agent config', + field: 'policy_id', + name: i18n.translate('xpack.ingestManager.enrollmentTokensList.policyTitle', { + defaultMessage: 'Agent policy', }), - render: (configId: string) => { - const config = agentConfigs.find((c) => c.id === configId); - const value = config ? config.name : configId; + render: (policyId: string) => { + const agentPolicy = agentPolicies.find((c) => c.id === policyId); + const value = agentPolicy ? agentPolicy.name : policyId; return ( {value} @@ -255,7 +255,7 @@ export const EnrollmentTokenListPage: React.FunctionComponent<{}> = () => { <> {flyoutOpen && ( { setFlyoutOpen(false); enrollmentAPIKeysRequest.sendRequest(); diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/setup_page/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/setup_page/index.tsx index ffd8591a642c1a..eeade9036df000 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/setup_page/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/setup_page/index.tsx @@ -134,7 +134,7 @@ export const SetupPage: React.FunctionComponent<{ @@ -190,7 +190,7 @@ xpack.security.authc.api_key.enabled: true`} diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/index.tsx index 1f46c4cc820cb9..3a0f2c3ea8d58e 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/index.tsx @@ -5,8 +5,8 @@ */ export { IngestManagerOverview } from './overview'; export { EPMApp } from './epm'; -export { AgentConfigApp } from './agent_config'; +export { AgentPolicyApp } from './agent_policy'; export { DataStreamApp } from './data_stream'; export { FleetApp } from './fleet'; -export type Section = 'overview' | 'epm' | 'agent_config' | 'fleet' | 'data_stream'; +export type Section = 'overview' | 'epm' | 'agent_policy' | 'fleet' | 'data_stream'; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/configuration_section.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/agent_policy_section.tsx similarity index 61% rename from x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/configuration_section.tsx rename to x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/agent_policy_section.tsx index 56aaba1d433212..617be92b3b1fe3 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/configuration_section.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/agent_policy_section.tsx @@ -15,15 +15,15 @@ import { } from '@elastic/eui'; import { OverviewPanel } from './overview_panel'; import { OverviewStats } from './overview_stats'; -import { useLink, useGetPackageConfigs } from '../../../hooks'; -import { AgentConfig } from '../../../types'; +import { useLink, useGetPackagePolicies } from '../../../hooks'; +import { AgentPolicy } from '../../../types'; import { Loading } from '../../fleet/components'; -export const OverviewConfigurationSection: React.FC<{ agentConfigs: AgentConfig[] }> = ({ - agentConfigs, +export const OverviewPolicySection: React.FC<{ agentPolicies: AgentPolicy[] }> = ({ + agentPolicies, }) => { const { getHref } = useLink(); - const packageConfigsRequest = useGetPackageConfigs({ + const packagePoliciesRequest = useGetPackagePolicies({ page: 1, perPage: 10000, }); @@ -31,39 +31,39 @@ export const OverviewConfigurationSection: React.FC<{ agentConfigs: AgentConfig[ return ( - {packageConfigsRequest.isLoading ? ( + {packagePoliciesRequest.isLoading ? ( ) : ( <> - + - + )} diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/agent_section.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/agent_section.tsx index 7e33589bffea12..d7b08bf5ffa3a3 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/agent_section.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/agent_section.tsx @@ -30,7 +30,7 @@ export const OverviewAgentSection = () => { })} tooltip={i18n.translate('xpack.ingestManager.overviewPageFleetPanelTooltip', { defaultMessage: - 'Use Fleet to enroll agents and manage their configurations from a central location.', + 'Use Fleet to enroll agents and manage their policies from a central location.', })} linkTo={getHref('fleet_agent_list')} linkToText={i18n.translate('xpack.ingestManager.overviewPageFleetPanelAction', { diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/integration_section.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/integration_section.tsx index ba16b47e73051f..1e138ae922afc9 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/integration_section.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/integration_section.tsx @@ -37,7 +37,7 @@ export const OverviewIntegrationSection: React.FC = () => { })} tooltip={i18n.translate('xpack.ingestManager.overviewPageIntegrationsPanelTooltip', { defaultMessage: - 'Browse and install integrations for the Elastic Stack. Add integrations to your agent configurations to start sending data.', + 'Browse and install integrations for the Elastic Stack. Add integrations to your agent policies to start sending data.', })} linkTo={getHref('integrations_all')} linkToText={i18n.translate('xpack.ingestManager.overviewPageIntegrationsPanelAction', { diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/index.tsx index ea7ae093ee59ad..187b701dc4167c 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/index.tsx @@ -16,10 +16,10 @@ import { import { FormattedMessage } from '@kbn/i18n/react'; import { i18n } from '@kbn/i18n'; import { WithHeaderLayout } from '../../layouts'; -import { useGetAgentConfigs, useBreadcrumbs } from '../../hooks'; +import { useGetAgentPolicies, useBreadcrumbs } from '../../hooks'; import { AgentEnrollmentFlyout } from '../fleet/components'; import { OverviewAgentSection } from './components/agent_section'; -import { OverviewConfigurationSection } from './components/configuration_section'; +import { OverviewPolicySection } from './components/agent_policy_section'; import { OverviewIntegrationSection } from './components/integration_section'; import { OverviewDatastreamSection } from './components/datastream_section'; @@ -29,12 +29,12 @@ export const IngestManagerOverview: React.FunctionComponent = () => { // Agent enrollment flyout state const [isEnrollmentFlyoutOpen, setIsEnrollmentFlyoutOpen] = useState(false); - // Agent configs required for enrollment flyout - const agentConfigsRequest = useGetAgentConfigs({ + // Agent policies required for enrollment flyout + const agentPoliciesRequest = useGetAgentPolicies({ page: 1, perPage: 1000, }); - const agentConfigs = agentConfigsRequest.data ? agentConfigsRequest.data.items : []; + const agentPolicies = agentPoliciesRequest.data ? agentPoliciesRequest.data.items : []; return ( {

@@ -93,14 +93,14 @@ export const IngestManagerOverview: React.FunctionComponent = () => { > {isEnrollmentFlyoutOpen && ( setIsEnrollmentFlyoutOpen(false)} /> )} - + diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/services/index.ts b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/services/index.ts index 9c3b84d0835b85..7d426c11c0aaba 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/services/index.ts +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/services/index.ts @@ -8,8 +8,8 @@ export { getFlattenedObject } from '../../../../../../../src/core/public'; export { AgentStatusKueryHelper, - agentConfigRouteService, - packageConfigRouteService, + agentPolicyRouteService, + packagePolicyRouteService, dataStreamRouteService, fleetSetupRouteService, agentRouteService, @@ -19,9 +19,9 @@ export { outputRoutesService, settingsRoutesService, appRoutesService, - packageToPackageConfigInputs, - storedPackageConfigsToAgentInputs, - configToYaml, + packageToPackagePolicyInputs, + storedPackagePoliciesToAgentInputs, + fullAgentPolicyToYaml, isPackageLimited, - doesAgentConfigAlreadyIncludePackage, + doesAgentPolicyAlreadyIncludePackage, } from '../../../../common'; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/types/index.ts b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/types/index.ts index dc27da18bc008f..80e27b7c4d0bf3 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/types/index.ts +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/types/index.ts @@ -9,40 +9,40 @@ export { // Object types Agent, AgentMetadata, - AgentConfig, - NewAgentConfig, + AgentPolicy, + NewAgentPolicy, AgentEvent, EnrollmentAPIKey, - PackageConfig, - NewPackageConfig, - UpdatePackageConfig, - PackageConfigInput, - PackageConfigInputStream, - PackageConfigConfigRecord, - PackageConfigConfigRecordEntry, + PackagePolicy, + NewPackagePolicy, + UpdatePackagePolicy, + PackagePolicyInput, + PackagePolicyInputStream, + PackagePolicyConfigRecord, + PackagePolicyConfigRecordEntry, Output, DataStream, // API schema - misc setup, status GetFleetStatusResponse, - // API schemas - Agent Config - GetAgentConfigsRequest, - GetAgentConfigsResponse, - GetAgentConfigsResponseItem, - GetOneAgentConfigResponse, - GetFullAgentConfigResponse, - CreateAgentConfigRequest, - CreateAgentConfigResponse, - UpdateAgentConfigRequest, - UpdateAgentConfigResponse, - CopyAgentConfigRequest, - CopyAgentConfigResponse, - DeleteAgentConfigRequest, - DeleteAgentConfigResponse, - // API schemas - Package config - CreatePackageConfigRequest, - CreatePackageConfigResponse, - UpdatePackageConfigRequest, - UpdatePackageConfigResponse, + // API schemas - Agent policy + GetAgentPoliciesRequest, + GetAgentPoliciesResponse, + GetAgentPoliciesResponseItem, + GetOneAgentPolicyResponse, + GetFullAgentPolicyResponse, + CreateAgentPolicyRequest, + CreateAgentPolicyResponse, + UpdateAgentPolicyRequest, + UpdateAgentPolicyResponse, + CopyAgentPolicyRequest, + CopyAgentPolicyResponse, + DeleteAgentPolicyRequest, + DeleteAgentPolicyResponse, + // API schemas - Package policy + CreatePackagePolicyRequest, + CreatePackagePolicyResponse, + UpdatePackagePolicyRequest, + UpdatePackagePolicyResponse, // API schemas - Data Streams GetDataStreamsResponse, // API schemas - Agents diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/types/intra_app_route_state.ts b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/types/intra_app_route_state.ts index 4fd770501ae3f2..c3faf7fc450d8f 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/types/intra_app_route_state.ts +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/types/intra_app_route_state.ts @@ -5,16 +5,16 @@ */ import { ApplicationStart } from 'kibana/public'; -import { PackageConfig } from './'; +import { PackagePolicy } from './'; /** - * Supported routing state for the create package config page routes + * Supported routing state for the create package policy page routes */ -export interface CreatePackageConfigRouteState { - /** On a successful save of the package config, use navigate to the given app */ +export interface CreatePackagePolicyRouteState { + /** On a successful save of the package policy, use navigate to the given app */ onSaveNavigateTo?: | Parameters - | ((newPackageConfig: PackageConfig) => Parameters); + | ((newPackagePolicy: PackagePolicy) => Parameters); /** On cancel, navigate to the given app */ onCancelNavigateTo?: Parameters; /** Url to be used on cancel links */ @@ -22,17 +22,17 @@ export interface CreatePackageConfigRouteState { } /** - * Supported routing state for the agent config details page routes with deploy agents action + * Supported routing state for the agent policy details page routes with deploy agents action */ -export interface AgentConfigDetailsDeployAgentAction { +export interface AgentPolicyDetailsDeployAgentAction { /** On done, navigate to the given app */ onDoneNavigateTo?: Parameters; } /** - * Supported routing state for the agent config details page routes with deploy agents action + * Supported routing state for the agent policy details page routes with deploy agents action */ -export interface AgentDetailsReassignConfigAction { +export interface AgentDetailsReassignPolicyAction { /** On done, navigate to the given app */ onDoneNavigateTo?: Parameters; } @@ -41,6 +41,6 @@ export interface AgentDetailsReassignConfigAction { * All possible Route states. */ export type AnyIntraAppRouteState = - | CreatePackageConfigRouteState - | AgentConfigDetailsDeployAgentAction - | AgentDetailsReassignConfigAction; + | CreatePackagePolicyRouteState + | AgentPolicyDetailsDeployAgentAction + | AgentDetailsReassignPolicyAction; diff --git a/x-pack/plugins/ingest_manager/public/index.ts b/x-pack/plugins/ingest_manager/public/index.ts index 866d17145b0758..75ba0e584230fb 100644 --- a/x-pack/plugins/ingest_manager/public/index.ts +++ b/x-pack/plugins/ingest_manager/public/index.ts @@ -13,10 +13,10 @@ export const plugin = (initializerContext: PluginInitializerContext) => { }; export { - CustomConfigurePackageConfigContent, - CustomConfigurePackageConfigProps, - registerPackageConfigComponent, -} from './applications/ingest_manager/sections/agent_config/create_package_config_page/components/custom_package_config'; + CustomConfigurePackagePolicyContent, + CustomConfigurePackagePolicyProps, + registerPackagePolicyComponent, +} from './applications/ingest_manager/sections/agent_policy/create_package_policy_page/components/custom_package_policy'; -export { NewPackageConfig } from './applications/ingest_manager/types'; +export { NewPackagePolicy } from './applications/ingest_manager/types'; export * from './applications/ingest_manager/types/intra_app_route_state'; diff --git a/x-pack/plugins/ingest_manager/public/plugin.ts b/x-pack/plugins/ingest_manager/public/plugin.ts index fde4e93f8e39ff..a8cc7b72eb17f2 100644 --- a/x-pack/plugins/ingest_manager/public/plugin.ts +++ b/x-pack/plugins/ingest_manager/public/plugin.ts @@ -25,7 +25,7 @@ import { TutorialDirectoryHeaderLink, TutorialModuleNotice, } from './applications/ingest_manager/components/home_integration'; -import { registerPackageConfigComponent } from './applications/ingest_manager/sections/agent_config/create_package_config_page/components/custom_package_config'; +import { registerPackagePolicyComponent } from './applications/ingest_manager/sections/agent_policy/create_package_policy_page/components/custom_package_policy'; export { IngestManagerConfigType } from '../common/types'; @@ -38,7 +38,7 @@ export interface IngestManagerSetup {} * Describes public IngestManager plugin contract returned at the `start` stage. */ export interface IngestManagerStart { - registerPackageConfigComponent: typeof registerPackageConfigComponent; + registerPackagePolicyComponent: typeof registerPackagePolicyComponent; isInitialized: () => Promise; } @@ -127,7 +127,7 @@ export class IngestManagerPlugin return successPromise; }, - registerPackageConfigComponent, + registerPackagePolicyComponent, }; } diff --git a/x-pack/plugins/ingest_manager/server/collectors/agent_collectors.ts b/x-pack/plugins/ingest_manager/server/collectors/agent_collectors.ts index 920b3362971718..fe5e5fa735b24d 100644 --- a/x-pack/plugins/ingest_manager/server/collectors/agent_collectors.ts +++ b/x-pack/plugins/ingest_manager/server/collectors/agent_collectors.ts @@ -23,7 +23,9 @@ export const getAgentUsage = async (soClient?: SavedObjectsClient): Promise { - const packageConfigs: NewPackageConfig[] = agentConfig.package_configs as NewPackageConfig[]; - return packageConfigs - .map((packageConfig) => packageConfig.package?.name) + const packagesInAgentPolicies = agentPolicies.items.map((agentPolicy) => { + const packagePolicies: NewPackagePolicy[] = agentPolicy.package_policies as NewPackagePolicy[]; + return packagePolicies + .map((packagePolicy) => packagePolicy.package?.name) .filter((packageName): packageName is string => packageName !== undefined); }); - const enabledPackages = _.uniq(_.flatten(packagesInConfigs)); + const enabledPackages = _.uniq(_.flatten(packagesInAgentPolicies)); return packagesSavedObjects.saved_objects.map((p) => { return { diff --git a/x-pack/plugins/ingest_manager/server/constants/index.ts b/x-pack/plugins/ingest_manager/server/constants/index.ts index 730d8cf7b172c1..54d2d876c75b12 100644 --- a/x-pack/plugins/ingest_manager/server/constants/index.ts +++ b/x-pack/plugins/ingest_manager/server/constants/index.ts @@ -10,8 +10,8 @@ export { AGENT_POLLING_THRESHOLD_MS, AGENT_POLLING_INTERVAL, AGENT_UPDATE_LAST_CHECKIN_INTERVAL_MS, - AGENT_CONFIG_ROLLOUT_RATE_LIMIT_REQUEST_PER_INTERVAL, - AGENT_CONFIG_ROLLOUT_RATE_LIMIT_INTERVAL_MS, + AGENT_POLICY_ROLLOUT_RATE_LIMIT_REQUEST_PER_INTERVAL, + AGENT_POLICY_ROLLOUT_RATE_LIMIT_INTERVAL_MS, AGENT_UPDATE_ACTIONS_INTERVAL_MS, INDEX_PATTERN_PLACEHOLDER_SUFFIX, // Routes @@ -19,9 +19,9 @@ export { PLUGIN_ID, EPM_API_ROUTES, DATA_STREAM_API_ROUTES, - PACKAGE_CONFIG_API_ROUTES, + PACKAGE_POLICY_API_ROUTES, AGENT_API_ROUTES, - AGENT_CONFIG_API_ROUTES, + AGENT_POLICY_API_ROUTES, FLEET_SETUP_API_ROUTES, ENROLLMENT_API_KEY_ROUTES, INSTALL_SCRIPT_API_ROUTES, @@ -33,14 +33,14 @@ export { AGENT_SAVED_OBJECT_TYPE, AGENT_EVENT_SAVED_OBJECT_TYPE, AGENT_ACTION_SAVED_OBJECT_TYPE, - AGENT_CONFIG_SAVED_OBJECT_TYPE, - PACKAGE_CONFIG_SAVED_OBJECT_TYPE, + AGENT_POLICY_SAVED_OBJECT_TYPE, + PACKAGE_POLICY_SAVED_OBJECT_TYPE, OUTPUT_SAVED_OBJECT_TYPE, PACKAGES_SAVED_OBJECT_TYPE, INDEX_PATTERN_SAVED_OBJECT_TYPE, ENROLLMENT_API_KEYS_SAVED_OBJECT_TYPE, GLOBAL_SETTINGS_SAVED_OBJECT_TYPE, // Defaults - DEFAULT_AGENT_CONFIG, + DEFAULT_AGENT_POLICY, DEFAULT_OUTPUT, } from '../../common'; diff --git a/x-pack/plugins/ingest_manager/server/index.ts b/x-pack/plugins/ingest_manager/server/index.ts index 9933266a441e20..962cddb2e411e6 100644 --- a/x-pack/plugins/ingest_manager/server/index.ts +++ b/x-pack/plugins/ingest_manager/server/index.ts @@ -7,8 +7,8 @@ import { schema, TypeOf } from '@kbn/config-schema'; import { PluginInitializerContext } from 'src/core/server'; import { IngestManagerPlugin } from './plugin'; import { - AGENT_CONFIG_ROLLOUT_RATE_LIMIT_INTERVAL_MS, - AGENT_CONFIG_ROLLOUT_RATE_LIMIT_REQUEST_PER_INTERVAL, + AGENT_POLICY_ROLLOUT_RATE_LIMIT_INTERVAL_MS, + AGENT_POLICY_ROLLOUT_RATE_LIMIT_REQUEST_PER_INTERVAL, } from '../common'; export { AgentService, ESIndexPatternService, getRegistryUrl } from './services'; export { @@ -39,11 +39,11 @@ export const config = { host: schema.maybe(schema.string()), ca_sha256: schema.maybe(schema.string()), }), - agentConfigRolloutRateLimitIntervalMs: schema.number({ - defaultValue: AGENT_CONFIG_ROLLOUT_RATE_LIMIT_INTERVAL_MS, + agentPolicyRolloutRateLimitIntervalMs: schema.number({ + defaultValue: AGENT_POLICY_ROLLOUT_RATE_LIMIT_INTERVAL_MS, }), - agentConfigRolloutRateLimitRequestPerInterval: schema.number({ - defaultValue: AGENT_CONFIG_ROLLOUT_RATE_LIMIT_REQUEST_PER_INTERVAL, + agentPolicyRolloutRateLimitRequestPerInterval: schema.number({ + defaultValue: AGENT_POLICY_ROLLOUT_RATE_LIMIT_REQUEST_PER_INTERVAL, }), }), }), @@ -51,7 +51,7 @@ export const config = { export type IngestManagerConfigType = TypeOf; -export { PackageConfigServiceInterface } from './services/package_config'; +export { PackagePolicyServiceInterface } from './services/package_policy'; export const plugin = (initializerContext: PluginInitializerContext) => { return new IngestManagerPlugin(initializerContext); diff --git a/x-pack/plugins/ingest_manager/server/integration_tests/router.test.ts b/x-pack/plugins/ingest_manager/server/integration_tests/router.test.ts index 9d671c629ef912..60ef6851bd9965 100644 --- a/x-pack/plugins/ingest_manager/server/integration_tests/router.test.ts +++ b/x-pack/plugins/ingest_manager/server/integration_tests/router.test.ts @@ -42,12 +42,12 @@ describe('ingestManager', () => { afterAll(async () => await root.shutdown()); - it('does not have agent config api', async () => { - await kbnTestServer.request.get(root, '/api/ingest_manager/agent_configs').expect(404); + it('does not have agent policy api', async () => { + await kbnTestServer.request.get(root, '/api/ingest_manager/agent_policies').expect(404); }); - it('does not have package configs api', async () => { - await kbnTestServer.request.get(root, '/api/ingest_manager/package_configs').expect(404); + it('does not have package policies api', async () => { + await kbnTestServer.request.get(root, '/api/ingest_manager/package_policies').expect(404); }); it('does not have EPM api', async () => { @@ -75,12 +75,12 @@ describe('ingestManager', () => { afterAll(async () => await root.shutdown()); - it('has agent config api', async () => { - await kbnTestServer.request.get(root, '/api/ingest_manager/agent_configs').expect(200); + it('has agent policy api', async () => { + await kbnTestServer.request.get(root, '/api/ingest_manager/agent_policies').expect(200); }); - it('has package configs api', async () => { - await kbnTestServer.request.get(root, '/api/ingest_manager/package_configs').expect(200); + it('has package policies api', async () => { + await kbnTestServer.request.get(root, '/api/ingest_manager/package_policies').expect(200); }); it('does not have EPM api', async () => { @@ -92,7 +92,7 @@ describe('ingestManager', () => { }); }); - // For now, only the manager routes (/agent_configs & /package_configs) are added + // For now, only the manager routes (/agent_policies & /package_policies) are added // EPM and ingest will be conditionally added when we enable these lines // https://github.com/jfsiii/kibana/blob/f73b54ebb7e0f6fc00efd8a6800a01eb2d9fb772/x-pack/plugins/ingest_manager/server/plugin.ts#L84 // adding tests to confirm the Fleet & EPM routes are never added @@ -114,12 +114,12 @@ describe('ingestManager', () => { afterAll(async () => await root.shutdown()); - it('has agent config api', async () => { - await kbnTestServer.request.get(root, '/api/ingest_manager/agent_configs').expect(200); + it('has agent policy api', async () => { + await kbnTestServer.request.get(root, '/api/ingest_manager/agent_policies').expect(200); }); - it('has package configs api', async () => { - await kbnTestServer.request.get(root, '/api/ingest_manager/package_configs').expect(200); + it('has package policies api', async () => { + await kbnTestServer.request.get(root, '/api/ingest_manager/package_policies').expect(200); }); it('does have EPM api', async () => { @@ -148,12 +148,12 @@ describe('ingestManager', () => { afterAll(async () => await root.shutdown()); - it('has agent config api', async () => { - await kbnTestServer.request.get(root, '/api/ingest_manager/agent_configs').expect(200); + it('has agent policy api', async () => { + await kbnTestServer.request.get(root, '/api/ingest_manager/agent_policies').expect(200); }); - it('has package configs api', async () => { - await kbnTestServer.request.get(root, '/api/ingest_manager/package_configs').expect(200); + it('has package policies api', async () => { + await kbnTestServer.request.get(root, '/api/ingest_manager/package_policies').expect(200); }); it('does not have EPM api', async () => { @@ -183,12 +183,12 @@ describe('ingestManager', () => { afterAll(async () => await root.shutdown()); - it('has agent config api', async () => { - await kbnTestServer.request.get(root, '/api/ingest_manager/agent_configs').expect(200); + it('has agent policy api', async () => { + await kbnTestServer.request.get(root, '/api/ingest_manager/agent_policies').expect(200); }); - it('has package configs api', async () => { - await kbnTestServer.request.get(root, '/api/ingest_manager/package_configs').expect(200); + it('has package policies api', async () => { + await kbnTestServer.request.get(root, '/api/ingest_manager/package_policies').expect(200); }); it('does have EPM api', async () => { diff --git a/x-pack/plugins/ingest_manager/server/mocks.ts b/x-pack/plugins/ingest_manager/server/mocks.ts index 52cd2947830875..18b58b5673651a 100644 --- a/x-pack/plugins/ingest_manager/server/mocks.ts +++ b/x-pack/plugins/ingest_manager/server/mocks.ts @@ -8,7 +8,7 @@ import { loggingSystemMock, savedObjectsServiceMock } from 'src/core/server/mock import { IngestManagerAppContext } from './plugin'; import { encryptedSavedObjectsMock } from '../../encrypted_saved_objects/server/mocks'; import { securityMock } from '../../security/server/mocks'; -import { PackageConfigServiceInterface } from './services/package_config'; +import { PackagePolicyServiceInterface } from './services/package_policy'; export const createAppContextStartContractMock = (): IngestManagerAppContext => { return { @@ -22,10 +22,10 @@ export const createAppContextStartContractMock = (): IngestManagerAppContext => }; }; -export const createPackageConfigServiceMock = () => { +export const createPackagePolicyServiceMock = () => { return { assignPackageStream: jest.fn(), - buildPackageConfigFromPackage: jest.fn(), + buildPackagePolicyFromPackage: jest.fn(), bulkCreate: jest.fn(), create: jest.fn(), delete: jest.fn(), @@ -33,5 +33,5 @@ export const createPackageConfigServiceMock = () => { getByIDs: jest.fn(), list: jest.fn(), update: jest.fn(), - } as jest.Mocked; + } as jest.Mocked; }; diff --git a/x-pack/plugins/ingest_manager/server/plugin.ts b/x-pack/plugins/ingest_manager/server/plugin.ts index e5e1194d59ecb9..ce1659176faaf7 100644 --- a/x-pack/plugins/ingest_manager/server/plugin.ts +++ b/x-pack/plugins/ingest_manager/server/plugin.ts @@ -25,8 +25,8 @@ import { PluginSetupContract as FeaturesPluginSetup } from '../../features/serve import { PLUGIN_ID, OUTPUT_SAVED_OBJECT_TYPE, - AGENT_CONFIG_SAVED_OBJECT_TYPE, - PACKAGE_CONFIG_SAVED_OBJECT_TYPE, + AGENT_POLICY_SAVED_OBJECT_TYPE, + PACKAGE_POLICY_SAVED_OBJECT_TYPE, PACKAGES_SAVED_OBJECT_TYPE, AGENT_SAVED_OBJECT_TYPE, AGENT_EVENT_SAVED_OBJECT_TYPE, @@ -36,9 +36,9 @@ import { registerSavedObjects, registerEncryptedSavedObjects } from './saved_obj import { registerLimitedConcurrencyRoutes, registerEPMRoutes, - registerPackageConfigRoutes, + registerPackagePolicyRoutes, registerDataStreamRoutes, - registerAgentConfigRoutes, + registerAgentPolicyRoutes, registerSetupRoutes, registerAgentRoutes, registerEnrollmentApiKeyRoutes, @@ -47,14 +47,14 @@ import { registerSettingsRoutes, registerAppRoutes, } from './routes'; -import { IngestManagerConfigType, NewPackageConfig } from '../common'; +import { IngestManagerConfigType, NewPackagePolicy } from '../common'; import { appContextService, licenseService, ESIndexPatternSavedObjectService, ESIndexPatternService, AgentService, - packageConfigService, + packagePolicyService, } from './services'; import { getAgentStatusById, @@ -95,8 +95,8 @@ export type IngestManagerSetupContract = void; const allSavedObjectTypes = [ OUTPUT_SAVED_OBJECT_TYPE, - AGENT_CONFIG_SAVED_OBJECT_TYPE, - PACKAGE_CONFIG_SAVED_OBJECT_TYPE, + AGENT_POLICY_SAVED_OBJECT_TYPE, + PACKAGE_POLICY_SAVED_OBJECT_TYPE, PACKAGES_SAVED_OBJECT_TYPE, AGENT_SAVED_OBJECT_TYPE, AGENT_EVENT_SAVED_OBJECT_TYPE, @@ -107,8 +107,8 @@ const allSavedObjectTypes = [ * Callbacks supported by the Ingest plugin */ export type ExternalCallback = [ - 'packageConfigCreate', - (newPackageConfig: NewPackageConfig) => Promise + 'packagePolicyCreate', + (newPackagePolicy: NewPackagePolicy) => Promise ]; export type ExternalCallbacksStorage = Map>; @@ -120,9 +120,9 @@ export interface IngestManagerStartContract { esIndexPatternService: ESIndexPatternService; agentService: AgentService; /** - * Services for Ingest's package configs + * Services for Ingest's package policies */ - packageConfigService: typeof packageConfigService; + packagePolicyService: typeof packagePolicyService; /** * Register callbacks for inclusion in ingest API processing * @param args @@ -214,8 +214,8 @@ export class IngestManagerPlugin // Register rest of routes only if security is enabled if (this.security) { registerSetupRoutes(router, config); - registerAgentConfigRoutes(router); - registerPackageConfigRoutes(router); + registerAgentPolicyRoutes(router); + registerPackagePolicyRoutes(router); registerOutputRoutes(router); registerSettingsRoutes(router); registerDataStreamRoutes(router); @@ -276,7 +276,7 @@ export class IngestManagerPlugin getAgentStatusById, authenticateAgentWithAccessToken, }, - packageConfigService, + packagePolicyService, registerExternalCallback: (...args: ExternalCallback) => { return appContextService.addExternalCallback(...args); }, diff --git a/x-pack/plugins/ingest_manager/server/routes/agent/handlers.ts b/x-pack/plugins/ingest_manager/server/routes/agent/handlers.ts index 6cfe3d5b762663..3e80a74dc2b11f 100644 --- a/x-pack/plugins/ingest_manager/server/routes/agent/handlers.ts +++ b/x-pack/plugins/ingest_manager/server/routes/agent/handlers.ts @@ -239,7 +239,7 @@ export const postAgentEnrollHandler: RequestHandler< const agent = await AgentService.enroll( soClient, request.body.type, - enrollmentAPIKey.config_id as string, + enrollmentAPIKey.policy_id as string, { userProvided: request.body.metadata.user_provided, local: request.body.metadata.local, @@ -310,7 +310,7 @@ export const putAgentsReassignHandler: RequestHandler< > = async (context, request, response) => { const soClient = context.core.savedObjects.client; try { - await AgentService.reassignAgent(soClient, request.params.agentId, request.body.config_id); + await AgentService.reassignAgent(soClient, request.params.agentId, request.body.policy_id); const body: PutAgentReassignResponse = { success: true, @@ -324,14 +324,17 @@ export const putAgentsReassignHandler: RequestHandler< } }; -export const getAgentStatusForConfigHandler: RequestHandler< +export const getAgentStatusForAgentPolicyHandler: RequestHandler< undefined, TypeOf > = async (context, request, response) => { const soClient = context.core.savedObjects.client; try { // TODO change path - const results = await AgentService.getAgentStatusForConfig(soClient, request.query.configId); + const results = await AgentService.getAgentStatusForAgentPolicy( + soClient, + request.query.policyId + ); const body: GetAgentStatusResponse = { results, success: true }; diff --git a/x-pack/plugins/ingest_manager/server/routes/agent/index.ts b/x-pack/plugins/ingest_manager/server/routes/agent/index.ts index b85d96186f2338..7c98ad31e5cdba 100644 --- a/x-pack/plugins/ingest_manager/server/routes/agent/index.ts +++ b/x-pack/plugins/ingest_manager/server/routes/agent/index.ts @@ -33,7 +33,7 @@ import { getAgentEventsHandler, postAgentCheckinHandler, postAgentEnrollHandler, - getAgentStatusForConfigHandler, + getAgentStatusForAgentPolicyHandler, putAgentsReassignHandler, } from './handlers'; import { postAgentAcksHandlerBuilder } from './acks_handlers'; @@ -158,13 +158,13 @@ export const registerRoutes = (router: IRouter) => { getAgentEventsHandler ); - // Get agent status for config + // Get agent status for policy router.get( { path: AGENT_API_ROUTES.STATUS_PATTERN, validate: GetAgentStatusRequestSchema, options: { tags: [`access:${PLUGIN_ID}-read`] }, }, - getAgentStatusForConfigHandler + getAgentStatusForAgentPolicyHandler ); }; diff --git a/x-pack/plugins/ingest_manager/server/routes/agent_config/index.ts b/x-pack/plugins/ingest_manager/server/routes/agent_config/index.ts deleted file mode 100644 index 95c7c13377366f..00000000000000 --- a/x-pack/plugins/ingest_manager/server/routes/agent_config/index.ts +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -import { IRouter } from 'src/core/server'; -import { PLUGIN_ID, AGENT_CONFIG_API_ROUTES } from '../../constants'; -import { - GetAgentConfigsRequestSchema, - GetOneAgentConfigRequestSchema, - CreateAgentConfigRequestSchema, - UpdateAgentConfigRequestSchema, - CopyAgentConfigRequestSchema, - DeleteAgentConfigRequestSchema, - GetFullAgentConfigRequestSchema, -} from '../../types'; -import { - getAgentConfigsHandler, - getOneAgentConfigHandler, - createAgentConfigHandler, - updateAgentConfigHandler, - copyAgentConfigHandler, - deleteAgentConfigsHandler, - getFullAgentConfig, - downloadFullAgentConfig, -} from './handlers'; - -export const registerRoutes = (router: IRouter) => { - // List - router.get( - { - path: AGENT_CONFIG_API_ROUTES.LIST_PATTERN, - validate: GetAgentConfigsRequestSchema, - options: { tags: [`access:${PLUGIN_ID}-read`] }, - }, - getAgentConfigsHandler - ); - - // Get one - router.get( - { - path: AGENT_CONFIG_API_ROUTES.INFO_PATTERN, - validate: GetOneAgentConfigRequestSchema, - options: { tags: [`access:${PLUGIN_ID}-read`] }, - }, - getOneAgentConfigHandler - ); - - // Create - router.post( - { - path: AGENT_CONFIG_API_ROUTES.CREATE_PATTERN, - validate: CreateAgentConfigRequestSchema, - options: { tags: [`access:${PLUGIN_ID}-all`] }, - }, - createAgentConfigHandler - ); - - // Update - router.put( - { - path: AGENT_CONFIG_API_ROUTES.UPDATE_PATTERN, - validate: UpdateAgentConfigRequestSchema, - options: { tags: [`access:${PLUGIN_ID}-all`] }, - }, - updateAgentConfigHandler - ); - - // Copy - router.post( - { - path: AGENT_CONFIG_API_ROUTES.COPY_PATTERN, - validate: CopyAgentConfigRequestSchema, - options: { tags: [`access:${PLUGIN_ID}-all`] }, - }, - copyAgentConfigHandler - ); - - // Delete - router.post( - { - path: AGENT_CONFIG_API_ROUTES.DELETE_PATTERN, - validate: DeleteAgentConfigRequestSchema, - options: { tags: [`access:${PLUGIN_ID}-all`] }, - }, - deleteAgentConfigsHandler - ); - - // Get one full agent config - router.get( - { - path: AGENT_CONFIG_API_ROUTES.FULL_INFO_PATTERN, - validate: GetFullAgentConfigRequestSchema, - options: { tags: [`access:${PLUGIN_ID}-read`] }, - }, - getFullAgentConfig - ); - - // Download one full agent config - router.get( - { - path: AGENT_CONFIG_API_ROUTES.FULL_INFO_DOWNLOAD_PATTERN, - validate: GetFullAgentConfigRequestSchema, - options: { tags: [`access:${PLUGIN_ID}-read`] }, - }, - downloadFullAgentConfig - ); -}; diff --git a/x-pack/plugins/ingest_manager/server/routes/agent_config/handlers.ts b/x-pack/plugins/ingest_manager/server/routes/agent_policy/handlers.ts similarity index 54% rename from x-pack/plugins/ingest_manager/server/routes/agent_config/handlers.ts rename to x-pack/plugins/ingest_manager/server/routes/agent_policy/handlers.ts index 4e4653ec023ce1..cc178e1038e2ea 100644 --- a/x-pack/plugins/ingest_manager/server/routes/agent_config/handlers.ts +++ b/x-pack/plugins/ingest_manager/server/routes/agent_policy/handlers.ts @@ -6,45 +6,45 @@ import { TypeOf } from '@kbn/config-schema'; import { RequestHandler, ResponseHeaders } from 'src/core/server'; import bluebird from 'bluebird'; -import { configToYaml } from '../../../common/services'; -import { appContextService, agentConfigService, packageConfigService } from '../../services'; +import { fullAgentPolicyToYaml } from '../../../common/services'; +import { appContextService, agentPolicyService, packagePolicyService } from '../../services'; import { listAgents } from '../../services/agents'; import { AGENT_SAVED_OBJECT_TYPE } from '../../constants'; import { - GetAgentConfigsRequestSchema, - GetOneAgentConfigRequestSchema, - CreateAgentConfigRequestSchema, - UpdateAgentConfigRequestSchema, - CopyAgentConfigRequestSchema, - DeleteAgentConfigRequestSchema, - GetFullAgentConfigRequestSchema, - AgentConfig, + GetAgentPoliciesRequestSchema, + GetOneAgentPolicyRequestSchema, + CreateAgentPolicyRequestSchema, + UpdateAgentPolicyRequestSchema, + CopyAgentPolicyRequestSchema, + DeleteAgentPolicyRequestSchema, + GetFullAgentPolicyRequestSchema, + AgentPolicy, DefaultPackages, - NewPackageConfig, + NewPackagePolicy, } from '../../types'; import { - GetAgentConfigsResponse, - GetAgentConfigsResponseItem, - GetOneAgentConfigResponse, - CreateAgentConfigResponse, - UpdateAgentConfigResponse, - CopyAgentConfigResponse, - DeleteAgentConfigResponse, - GetFullAgentConfigResponse, + GetAgentPoliciesResponse, + GetAgentPoliciesResponseItem, + GetOneAgentPolicyResponse, + CreateAgentPolicyResponse, + UpdateAgentPolicyResponse, + CopyAgentPolicyResponse, + DeleteAgentPolicyResponse, + GetFullAgentPolicyResponse, } from '../../../common'; -export const getAgentConfigsHandler: RequestHandler< +export const getAgentPoliciesHandler: RequestHandler< undefined, - TypeOf + TypeOf > = async (context, request, response) => { const soClient = context.core.savedObjects.client; - const { full: withPackageConfigs = false, ...restOfQuery } = request.query; + const { full: withPackagePolicies = false, ...restOfQuery } = request.query; try { - const { items, total, page, perPage } = await agentConfigService.list(soClient, { - withPackageConfigs, + const { items, total, page, perPage } = await agentPolicyService.list(soClient, { + withPackagePolicies, ...restOfQuery, }); - const body: GetAgentConfigsResponse = { + const body: GetAgentPoliciesResponse = { items, total, page, @@ -54,13 +54,13 @@ export const getAgentConfigsHandler: RequestHandler< await bluebird.map( items, - (agentConfig: GetAgentConfigsResponseItem) => + (agentPolicy: GetAgentPoliciesResponseItem) => listAgents(soClient, { showInactive: false, perPage: 0, page: 1, - kuery: `${AGENT_SAVED_OBJECT_TYPE}.config_id:${agentConfig.id}`, - }).then(({ total: agentTotal }) => (agentConfig.agents = agentTotal)), + kuery: `${AGENT_SAVED_OBJECT_TYPE}.policy_id:${agentPolicy.id}`, + }).then(({ total: agentTotal }) => (agentPolicy.agents = agentTotal)), { concurrency: 10 } ); @@ -73,15 +73,15 @@ export const getAgentConfigsHandler: RequestHandler< } }; -export const getOneAgentConfigHandler: RequestHandler> = async (context, request, response) => { const soClient = context.core.savedObjects.client; try { - const agentConfig = await agentConfigService.get(soClient, request.params.agentConfigId); - if (agentConfig) { - const body: GetOneAgentConfigResponse = { - item: agentConfig, + const agentPolicy = await agentPolicyService.get(soClient, request.params.agentPolicyId); + if (agentPolicy) { + const body: GetOneAgentPolicyResponse = { + item: agentPolicy, success: true, }; return response.ok({ @@ -90,7 +90,7 @@ export const getOneAgentConfigHandler: RequestHandler, - TypeOf + TypeOf, + TypeOf > = async (context, request, response) => { const soClient = context.core.savedObjects.client; const callCluster = context.core.elasticsearch.legacy.client.callAsCurrentUser; @@ -112,35 +112,35 @@ export const createAgentConfigHandler: RequestHandler< const withSysMonitoring = request.query.sys_monitoring ?? false; try { // eslint-disable-next-line prefer-const - let [agentConfig, newSysPackageConfig] = await Promise.all< - AgentConfig, - NewPackageConfig | undefined + let [agentPolicy, newSysPackagePolicy] = await Promise.all< + AgentPolicy, + NewPackagePolicy | undefined >([ - agentConfigService.create(soClient, request.body, { + agentPolicyService.create(soClient, request.body, { user, }), - // If needed, retrieve System package information and build a new package config for the system package - // NOTE: we ignore failures in attempting to create package config, since config might have been created + // If needed, retrieve System package information and build a new package policy for the system package + // NOTE: we ignore failures in attempting to create package policy, since agent policy might have been created // successfully withSysMonitoring - ? packageConfigService - .buildPackageConfigFromPackage(soClient, DefaultPackages.system) + ? packagePolicyService + .buildPackagePolicyFromPackage(soClient, DefaultPackages.system) .catch(() => undefined) : undefined, ]); - // Create the system monitoring package config and add it to agent config. - if (withSysMonitoring && newSysPackageConfig !== undefined && agentConfig !== undefined) { - newSysPackageConfig.config_id = agentConfig.id; - newSysPackageConfig.namespace = agentConfig.namespace; - await packageConfigService.create(soClient, callCluster, newSysPackageConfig, { + // Create the system monitoring package policy and add it to agent policy. + if (withSysMonitoring && newSysPackagePolicy !== undefined && agentPolicy !== undefined) { + newSysPackagePolicy.policy_id = agentPolicy.id; + newSysPackagePolicy.namespace = agentPolicy.namespace; + await packagePolicyService.create(soClient, callCluster, newSysPackagePolicy, { user, - bumpConfigRevision: false, + bumpRevision: false, }); } - const body: CreateAgentConfigResponse = { - item: agentConfig, + const body: CreateAgentPolicyResponse = { + item: agentPolicy, success: true, }; @@ -155,23 +155,23 @@ export const createAgentConfigHandler: RequestHandler< } }; -export const updateAgentConfigHandler: RequestHandler< - TypeOf, +export const updateAgentPolicyHandler: RequestHandler< + TypeOf, unknown, - TypeOf + TypeOf > = async (context, request, response) => { const soClient = context.core.savedObjects.client; const user = await appContextService.getSecurity()?.authc.getCurrentUser(request); try { - const agentConfig = await agentConfigService.update( + const agentPolicy = await agentPolicyService.update( soClient, - request.params.agentConfigId, + request.params.agentPolicyId, request.body, { user: user || undefined, } ); - const body: UpdateAgentConfigResponse = { item: agentConfig, success: true }; + const body: UpdateAgentPolicyResponse = { item: agentPolicy, success: true }; return response.ok({ body, }); @@ -183,23 +183,23 @@ export const updateAgentConfigHandler: RequestHandler< } }; -export const copyAgentConfigHandler: RequestHandler< - TypeOf, +export const copyAgentPolicyHandler: RequestHandler< + TypeOf, unknown, - TypeOf + TypeOf > = async (context, request, response) => { const soClient = context.core.savedObjects.client; const user = await appContextService.getSecurity()?.authc.getCurrentUser(request); try { - const agentConfig = await agentConfigService.copy( + const agentPolicy = await agentPolicyService.copy( soClient, - request.params.agentConfigId, + request.params.agentPolicyId, request.body, { user: user || undefined, } ); - const body: CopyAgentConfigResponse = { item: agentConfig, success: true }; + const body: CopyAgentPolicyResponse = { item: agentPolicy, success: true }; return response.ok({ body, }); @@ -211,16 +211,16 @@ export const copyAgentConfigHandler: RequestHandler< } }; -export const deleteAgentConfigsHandler: RequestHandler< +export const deleteAgentPoliciesHandler: RequestHandler< unknown, unknown, - TypeOf + TypeOf > = async (context, request, response) => { const soClient = context.core.savedObjects.client; try { - const body: DeleteAgentConfigResponse = await agentConfigService.delete( + const body: DeleteAgentPolicyResponse = await agentPolicyService.delete( soClient, - request.body.agentConfigId + request.body.agentPolicyId ); return response.ok({ body, @@ -233,21 +233,21 @@ export const deleteAgentConfigsHandler: RequestHandler< } }; -export const getFullAgentConfig: RequestHandler< - TypeOf, - TypeOf +export const getFullAgentPolicy: RequestHandler< + TypeOf, + TypeOf > = async (context, request, response) => { const soClient = context.core.savedObjects.client; try { - const fullAgentConfig = await agentConfigService.getFullConfig( + const fullAgentPolicy = await agentPolicyService.getFullAgentPolicy( soClient, - request.params.agentConfigId, + request.params.agentPolicyId, { standalone: request.query.standalone === true } ); - if (fullAgentConfig) { - const body: GetFullAgentConfigResponse = { - item: fullAgentConfig, + if (fullAgentPolicy) { + const body: GetFullAgentPolicyResponse = { + item: fullAgentPolicy, success: true, }; return response.ok({ @@ -256,7 +256,7 @@ export const getFullAgentConfig: RequestHandler< } else { return response.customError({ statusCode: 404, - body: { message: 'Agent config not found' }, + body: { message: 'Agent policy not found' }, }); } } catch (e) { @@ -267,21 +267,21 @@ export const getFullAgentConfig: RequestHandler< } }; -export const downloadFullAgentConfig: RequestHandler< - TypeOf, - TypeOf +export const downloadFullAgentPolicy: RequestHandler< + TypeOf, + TypeOf > = async (context, request, response) => { const soClient = context.core.savedObjects.client; const { - params: { agentConfigId }, + params: { agentPolicyId }, } = request; try { - const fullAgentConfig = await agentConfigService.getFullConfig(soClient, agentConfigId, { + const fullAgentPolicy = await agentPolicyService.getFullAgentPolicy(soClient, agentPolicyId, { standalone: request.query.standalone === true, }); - if (fullAgentConfig) { - const body = configToYaml(fullAgentConfig); + if (fullAgentPolicy) { + const body = fullAgentPolicyToYaml(fullAgentPolicy); const headers: ResponseHeaders = { 'content-type': 'text/x-yaml', 'content-disposition': `attachment; filename="elastic-agent.yml"`, @@ -293,7 +293,7 @@ export const downloadFullAgentConfig: RequestHandler< } else { return response.customError({ statusCode: 404, - body: { message: 'Agent config not found' }, + body: { message: 'Agent policy not found' }, }); } } catch (e) { diff --git a/x-pack/plugins/ingest_manager/server/routes/agent_policy/index.ts b/x-pack/plugins/ingest_manager/server/routes/agent_policy/index.ts new file mode 100644 index 00000000000000..7a6af61f51006c --- /dev/null +++ b/x-pack/plugins/ingest_manager/server/routes/agent_policy/index.ts @@ -0,0 +1,108 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { IRouter } from 'src/core/server'; +import { PLUGIN_ID, AGENT_POLICY_API_ROUTES } from '../../constants'; +import { + GetAgentPoliciesRequestSchema, + GetOneAgentPolicyRequestSchema, + CreateAgentPolicyRequestSchema, + UpdateAgentPolicyRequestSchema, + CopyAgentPolicyRequestSchema, + DeleteAgentPolicyRequestSchema, + GetFullAgentPolicyRequestSchema, +} from '../../types'; +import { + getAgentPoliciesHandler, + getOneAgentPolicyHandler, + createAgentPolicyHandler, + updateAgentPolicyHandler, + copyAgentPolicyHandler, + deleteAgentPoliciesHandler, + getFullAgentPolicy, + downloadFullAgentPolicy, +} from './handlers'; + +export const registerRoutes = (router: IRouter) => { + // List + router.get( + { + path: AGENT_POLICY_API_ROUTES.LIST_PATTERN, + validate: GetAgentPoliciesRequestSchema, + options: { tags: [`access:${PLUGIN_ID}-read`] }, + }, + getAgentPoliciesHandler + ); + + // Get one + router.get( + { + path: AGENT_POLICY_API_ROUTES.INFO_PATTERN, + validate: GetOneAgentPolicyRequestSchema, + options: { tags: [`access:${PLUGIN_ID}-read`] }, + }, + getOneAgentPolicyHandler + ); + + // Create + router.post( + { + path: AGENT_POLICY_API_ROUTES.CREATE_PATTERN, + validate: CreateAgentPolicyRequestSchema, + options: { tags: [`access:${PLUGIN_ID}-all`] }, + }, + createAgentPolicyHandler + ); + + // Update + router.put( + { + path: AGENT_POLICY_API_ROUTES.UPDATE_PATTERN, + validate: UpdateAgentPolicyRequestSchema, + options: { tags: [`access:${PLUGIN_ID}-all`] }, + }, + updateAgentPolicyHandler + ); + + // Copy + router.post( + { + path: AGENT_POLICY_API_ROUTES.COPY_PATTERN, + validate: CopyAgentPolicyRequestSchema, + options: { tags: [`access:${PLUGIN_ID}-all`] }, + }, + copyAgentPolicyHandler + ); + + // Delete + router.post( + { + path: AGENT_POLICY_API_ROUTES.DELETE_PATTERN, + validate: DeleteAgentPolicyRequestSchema, + options: { tags: [`access:${PLUGIN_ID}-all`] }, + }, + deleteAgentPoliciesHandler + ); + + // Get one full agent policy + router.get( + { + path: AGENT_POLICY_API_ROUTES.FULL_INFO_PATTERN, + validate: GetFullAgentPolicyRequestSchema, + options: { tags: [`access:${PLUGIN_ID}-read`] }, + }, + getFullAgentPolicy + ); + + // Download one full agent policy + router.get( + { + path: AGENT_POLICY_API_ROUTES.FULL_INFO_DOWNLOAD_PATTERN, + validate: GetFullAgentPolicyRequestSchema, + options: { tags: [`access:${PLUGIN_ID}-read`] }, + }, + downloadFullAgentPolicy + ); +}; diff --git a/x-pack/plugins/ingest_manager/server/routes/enrollment_api_key/handler.ts b/x-pack/plugins/ingest_manager/server/routes/enrollment_api_key/handler.ts index 94fc6de6096139..2d6e2f67225e33 100644 --- a/x-pack/plugins/ingest_manager/server/routes/enrollment_api_key/handler.ts +++ b/x-pack/plugins/ingest_manager/server/routes/enrollment_api_key/handler.ts @@ -51,7 +51,7 @@ export const postEnrollmentApiKeyHandler: RequestHandler< const apiKey = await APIKeyService.generateEnrollmentAPIKey(soClient, { name: request.body.name, expiration: request.body.expiration, - configId: request.body.config_id, + agentPolicyId: request.body.policy_id, }); const body: PostEnrollmentAPIKeyResponse = { item: apiKey, success: true, action: 'created' }; diff --git a/x-pack/plugins/ingest_manager/server/routes/index.ts b/x-pack/plugins/ingest_manager/server/routes/index.ts index 87be3a80cea963..0743270fd71215 100644 --- a/x-pack/plugins/ingest_manager/server/routes/index.ts +++ b/x-pack/plugins/ingest_manager/server/routes/index.ts @@ -3,8 +3,8 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -export { registerRoutes as registerAgentConfigRoutes } from './agent_config'; -export { registerRoutes as registerPackageConfigRoutes } from './package_config'; +export { registerRoutes as registerAgentPolicyRoutes } from './agent_policy'; +export { registerRoutes as registerPackagePolicyRoutes } from './package_policy'; export { registerRoutes as registerDataStreamRoutes } from './data_streams'; export { registerRoutes as registerEPMRoutes } from './epm'; export { registerRoutes as registerSetupRoutes } from './setup'; diff --git a/x-pack/plugins/ingest_manager/server/routes/package_config/index.ts b/x-pack/plugins/ingest_manager/server/routes/package_config/index.ts deleted file mode 100644 index 1da045e0529975..00000000000000 --- a/x-pack/plugins/ingest_manager/server/routes/package_config/index.ts +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -import { IRouter } from 'src/core/server'; -import { PLUGIN_ID, PACKAGE_CONFIG_API_ROUTES } from '../../constants'; -import { - GetPackageConfigsRequestSchema, - GetOnePackageConfigRequestSchema, - CreatePackageConfigRequestSchema, - UpdatePackageConfigRequestSchema, - DeletePackageConfigsRequestSchema, -} from '../../types'; -import { - getPackageConfigsHandler, - getOnePackageConfigHandler, - createPackageConfigHandler, - updatePackageConfigHandler, - deletePackageConfigHandler, -} from './handlers'; - -export const registerRoutes = (router: IRouter) => { - // List - router.get( - { - path: PACKAGE_CONFIG_API_ROUTES.LIST_PATTERN, - validate: GetPackageConfigsRequestSchema, - options: { tags: [`access:${PLUGIN_ID}-read`] }, - }, - getPackageConfigsHandler - ); - - // Get one - router.get( - { - path: PACKAGE_CONFIG_API_ROUTES.INFO_PATTERN, - validate: GetOnePackageConfigRequestSchema, - options: { tags: [`access:${PLUGIN_ID}-read`] }, - }, - getOnePackageConfigHandler - ); - - // Create - router.post( - { - path: PACKAGE_CONFIG_API_ROUTES.CREATE_PATTERN, - validate: CreatePackageConfigRequestSchema, - options: { tags: [`access:${PLUGIN_ID}-all`] }, - }, - createPackageConfigHandler - ); - - // Update - router.put( - { - path: PACKAGE_CONFIG_API_ROUTES.UPDATE_PATTERN, - validate: UpdatePackageConfigRequestSchema, - options: { tags: [`access:${PLUGIN_ID}-all`] }, - }, - updatePackageConfigHandler - ); - - // Delete - router.post( - { - path: PACKAGE_CONFIG_API_ROUTES.DELETE_PATTERN, - validate: DeletePackageConfigsRequestSchema, - options: { tags: [`access:${PLUGIN_ID}`] }, - }, - deletePackageConfigHandler - ); -}; diff --git a/x-pack/plugins/ingest_manager/server/routes/package_config/handlers.test.ts b/x-pack/plugins/ingest_manager/server/routes/package_policy/handlers.test.ts similarity index 83% rename from x-pack/plugins/ingest_manager/server/routes/package_config/handlers.test.ts rename to x-pack/plugins/ingest_manager/server/routes/package_policy/handlers.test.ts index 85ecc5027d64d6..db23d6a139f209 100644 --- a/x-pack/plugins/ingest_manager/server/routes/package_config/handlers.test.ts +++ b/x-pack/plugins/ingest_manager/server/routes/package_policy/handlers.test.ts @@ -7,23 +7,23 @@ import { httpServerMock, httpServiceMock } from 'src/core/server/mocks'; import { IRouter, KibanaRequest, Logger, RequestHandler, RouteConfig } from 'kibana/server'; import { registerRoutes } from './index'; -import { PACKAGE_CONFIG_API_ROUTES } from '../../../common/constants'; +import { PACKAGE_POLICY_API_ROUTES } from '../../../common/constants'; import { xpackMocks } from '../../../../../mocks'; import { appContextService } from '../../services'; import { createAppContextStartContractMock } from '../../mocks'; -import { PackageConfigServiceInterface, ExternalCallback } from '../..'; -import { CreatePackageConfigRequestSchema } from '../../types/rest_spec'; -import { packageConfigService } from '../../services'; +import { PackagePolicyServiceInterface, ExternalCallback } from '../..'; +import { CreatePackagePolicyRequestSchema } from '../../types/rest_spec'; +import { packagePolicyService } from '../../services'; -const packageConfigServiceMock = packageConfigService as jest.Mocked; +const packagePolicyServiceMock = packagePolicyService as jest.Mocked; -jest.mock('../../services/package_config', (): { - packageConfigService: jest.Mocked; +jest.mock('../../services/package_policy', (): { + packagePolicyService: jest.Mocked; } => { return { - packageConfigService: { + packagePolicyService: { assignPackageStream: jest.fn((packageInfo, dataInputs) => Promise.resolve(dataInputs)), - buildPackageConfigFromPackage: jest.fn(), + buildPackagePolicyFromPackage: jest.fn(), bulkCreate: jest.fn(), create: jest.fn((soClient, callCluster, newData) => Promise.resolve({ @@ -52,7 +52,7 @@ jest.mock('../../services/epm/packages', () => { }; }); -describe('When calling package config', () => { +describe('When calling package policy', () => { let routerMock: jest.Mocked; let routeHandler: RequestHandler; let routeConfig: RouteConfig; @@ -77,19 +77,19 @@ describe('When calling package config', () => { describe('create api handler', () => { const getCreateKibanaRequest = ( - newData?: typeof CreatePackageConfigRequestSchema.body - ): KibanaRequest => { + newData?: typeof CreatePackagePolicyRequestSchema.body + ): KibanaRequest => { return httpServerMock.createKibanaRequest< undefined, undefined, - typeof CreatePackageConfigRequestSchema.body + typeof CreatePackagePolicyRequestSchema.body >({ path: routeConfig.path, method: 'post', body: newData || { name: 'endpoint-1', description: '', - config_id: 'a5ca00c0-b30c-11ea-9732-1bb05811278c', + policy_id: 'a5ca00c0-b30c-11ea-9732-1bb05811278c', enabled: true, output_id: '', inputs: [], @@ -102,7 +102,7 @@ describe('When calling package config', () => { // Set the routeConfig and routeHandler to the Create API beforeAll(() => { [routeConfig, routeHandler] = routerMock.post.mock.calls.find(([{ path }]) => - path.startsWith(PACKAGE_CONFIG_API_ROUTES.CREATE_PATTERN) + path.startsWith(PACKAGE_POLICY_API_ROUTES.CREATE_PATTERN) )!; }); @@ -151,8 +151,8 @@ describe('When calling package config', () => { }); beforeEach(() => { - appContextService.addExternalCallback('packageConfigCreate', callbackOne); - appContextService.addExternalCallback('packageConfigCreate', callbackTwo); + appContextService.addExternalCallback('packagePolicyCreate', callbackOne); + appContextService.addExternalCallback('packagePolicyCreate', callbackTwo); }); afterEach(() => (callbackCallingOrder.length = 0)); @@ -164,12 +164,12 @@ describe('When calling package config', () => { expect(callbackCallingOrder).toEqual(['one', 'two']); }); - it('should feed package config returned by last callback', async () => { + it('should feed package policy returned by last callback', async () => { const request = getCreateKibanaRequest(); await routeHandler(context, request, response); expect(response.ok).toHaveBeenCalled(); expect(callbackOne).toHaveBeenCalledWith({ - config_id: 'a5ca00c0-b30c-11ea-9732-1bb05811278c', + policy_id: 'a5ca00c0-b30c-11ea-9732-1bb05811278c', description: '', enabled: true, inputs: [], @@ -183,7 +183,7 @@ describe('When calling package config', () => { }, }); expect(callbackTwo).toHaveBeenCalledWith({ - config_id: 'a5ca00c0-b30c-11ea-9732-1bb05811278c', + policy_id: 'a5ca00c0-b30c-11ea-9732-1bb05811278c', description: '', enabled: true, inputs: [ @@ -213,8 +213,8 @@ describe('When calling package config', () => { const request = getCreateKibanaRequest(); await routeHandler(context, request, response); expect(response.ok).toHaveBeenCalled(); - expect(packageConfigServiceMock.create.mock.calls[0][2]).toEqual({ - config_id: 'a5ca00c0-b30c-11ea-9732-1bb05811278c', + expect(packagePolicyServiceMock.create.mock.calls[0][2]).toEqual({ + policy_id: 'a5ca00c0-b30c-11ea-9732-1bb05811278c', description: '', enabled: true, inputs: [ @@ -268,8 +268,8 @@ describe('When calling package config', () => { }); beforeEach(() => { - appContextService.addExternalCallback('packageConfigCreate', callbackThree); - appContextService.addExternalCallback('packageConfigCreate', callbackFour); + appContextService.addExternalCallback('packagePolicyCreate', callbackThree); + appContextService.addExternalCallback('packagePolicyCreate', callbackFour); }); it('should skip over callback exceptions and still execute other callbacks', async () => { @@ -285,17 +285,17 @@ describe('When calling package config', () => { await routeHandler(context, request, response); expect(response.ok).toHaveBeenCalled(); expect(errorLogger.mock.calls).toEqual([ - ['An external registered [packageConfigCreate] callback failed when executed'], + ['An external registered [packagePolicyCreate] callback failed when executed'], [new Error('callbackThree threw error on purpose')], ]); }); - it('should create package config with last successful returned package config', async () => { + it('should create package policy with last successful returned package policy', async () => { const request = getCreateKibanaRequest(); await routeHandler(context, request, response); expect(response.ok).toHaveBeenCalled(); - expect(packageConfigServiceMock.create.mock.calls[0][2]).toEqual({ - config_id: 'a5ca00c0-b30c-11ea-9732-1bb05811278c', + expect(packagePolicyServiceMock.create.mock.calls[0][2]).toEqual({ + policy_id: 'a5ca00c0-b30c-11ea-9732-1bb05811278c', description: '', enabled: true, inputs: [ diff --git a/x-pack/plugins/ingest_manager/server/routes/package_config/handlers.ts b/x-pack/plugins/ingest_manager/server/routes/package_policy/handlers.ts similarity index 61% rename from x-pack/plugins/ingest_manager/server/routes/package_config/handlers.ts rename to x-pack/plugins/ingest_manager/server/routes/package_policy/handlers.ts index d2820cdbeb6c8a..d19a73604b4f06 100644 --- a/x-pack/plugins/ingest_manager/server/routes/package_config/handlers.ts +++ b/x-pack/plugins/ingest_manager/server/routes/package_policy/handlers.ts @@ -6,25 +6,25 @@ import { TypeOf } from '@kbn/config-schema'; import Boom from 'boom'; import { RequestHandler, SavedObjectsErrorHelpers } from '../../../../../../src/core/server'; -import { appContextService, packageConfigService } from '../../services'; +import { appContextService, packagePolicyService } from '../../services'; import { getPackageInfo } from '../../services/epm/packages'; import { - GetPackageConfigsRequestSchema, - GetOnePackageConfigRequestSchema, - CreatePackageConfigRequestSchema, - UpdatePackageConfigRequestSchema, - DeletePackageConfigsRequestSchema, - NewPackageConfig, + GetPackagePoliciesRequestSchema, + GetOnePackagePolicyRequestSchema, + CreatePackagePolicyRequestSchema, + UpdatePackagePolicyRequestSchema, + DeletePackagePoliciesRequestSchema, + NewPackagePolicy, } from '../../types'; -import { CreatePackageConfigResponse, DeletePackageConfigsResponse } from '../../../common'; +import { CreatePackagePolicyResponse, DeletePackagePoliciesResponse } from '../../../common'; -export const getPackageConfigsHandler: RequestHandler< +export const getPackagePoliciesHandler: RequestHandler< undefined, - TypeOf + TypeOf > = async (context, request, response) => { const soClient = context.core.savedObjects.client; try { - const { items, total, page, perPage } = await packageConfigService.list( + const { items, total, page, perPage } = await packagePolicyService.list( soClient, request.query ); @@ -45,20 +45,20 @@ export const getPackageConfigsHandler: RequestHandler< } }; -export const getOnePackageConfigHandler: RequestHandler> = async (context, request, response) => { const soClient = context.core.savedObjects.client; - const { packageConfigId } = request.params; + const { packagePolicyId } = request.params; const notFoundResponse = () => - response.notFound({ body: { message: `Package config ${packageConfigId} not found` } }); + response.notFound({ body: { message: `Package policy ${packagePolicyId} not found` } }); try { - const packageConfig = await packageConfigService.get(soClient, packageConfigId); - if (packageConfig) { + const packagePolicy = await packagePolicyService.get(soClient, packagePolicyId); + if (packagePolicy) { return response.ok({ body: { - item: packageConfig, + item: packagePolicy, success: true, }, }); @@ -77,10 +77,10 @@ export const getOnePackageConfigHandler: RequestHandler + TypeOf > = async (context, request, response) => { const soClient = context.core.savedObjects.client; const callCluster = context.core.elasticsearch.legacy.client.callAsCurrentUser; @@ -88,21 +88,21 @@ export const createPackageConfigHandler: RequestHandler< const logger = appContextService.getLogger(); let newData = { ...request.body }; try { - // If we have external callbacks, then process those now before creating the actual package config - const externalCallbacks = appContextService.getExternalCallbacks('packageConfigCreate'); + // If we have external callbacks, then process those now before creating the actual package policy + const externalCallbacks = appContextService.getExternalCallbacks('packagePolicyCreate'); if (externalCallbacks && externalCallbacks.size > 0) { - let updatedNewData: NewPackageConfig = newData; + let updatedNewData: NewPackagePolicy = newData; for (const callback of externalCallbacks) { try { // ensure that the returned value by the callback passes schema validation - updatedNewData = CreatePackageConfigRequestSchema.body.validate( + updatedNewData = CreatePackagePolicyRequestSchema.body.validate( await callback(updatedNewData) ); } catch (error) { // Log the error, but keep going and process the other callbacks logger.error( - 'An external registered [packageConfigCreate] callback failed when executed' + 'An external registered [packagePolicyCreate] callback failed when executed' ); logger.error(error); } @@ -111,11 +111,11 @@ export const createPackageConfigHandler: RequestHandler< newData = updatedNewData; } - // Create package config - const packageConfig = await packageConfigService.create(soClient, callCluster, newData, { + // Create package policy + const packagePolicy = await packagePolicyService.create(soClient, callCluster, newData, { user, }); - const body: CreatePackageConfigResponse = { item: packageConfig, success: true }; + const body: CreatePackagePolicyResponse = { item: packagePolicy, success: true }; return response.ok({ body, }); @@ -128,42 +128,42 @@ export const createPackageConfigHandler: RequestHandler< } }; -export const updatePackageConfigHandler: RequestHandler< - TypeOf, +export const updatePackagePolicyHandler: RequestHandler< + TypeOf, unknown, - TypeOf + TypeOf > = async (context, request, response) => { const soClient = context.core.savedObjects.client; const user = (await appContextService.getSecurity()?.authc.getCurrentUser(request)) || undefined; try { - const packageConfig = await packageConfigService.get(soClient, request.params.packageConfigId); + const packagePolicy = await packagePolicyService.get(soClient, request.params.packagePolicyId); - if (!packageConfig) { - throw Boom.notFound('Package config not found'); + if (!packagePolicy) { + throw Boom.notFound('Package policy not found'); } const newData = { ...request.body }; - const pkg = newData.package || packageConfig.package; - const inputs = newData.inputs || packageConfig.inputs; + const pkg = newData.package || packagePolicy.package; + const inputs = newData.inputs || packagePolicy.inputs; if (pkg && (newData.inputs || newData.package)) { const pkgInfo = await getPackageInfo({ savedObjectsClient: soClient, pkgName: pkg.name, pkgVersion: pkg.version, }); - newData.inputs = (await packageConfigService.assignPackageStream(pkgInfo, inputs)) as TypeOf< - typeof CreatePackageConfigRequestSchema.body + newData.inputs = (await packagePolicyService.assignPackageStream(pkgInfo, inputs)) as TypeOf< + typeof CreatePackagePolicyRequestSchema.body >['inputs']; } - const updatedPackageConfig = await packageConfigService.update( + const updatedPackagePolicy = await packagePolicyService.update( soClient, - request.params.packageConfigId, + request.params.packagePolicyId, newData, { user } ); return response.ok({ - body: { item: updatedPackageConfig, success: true }, + body: { item: updatedPackagePolicy, success: true }, }); } catch (e) { return response.customError({ @@ -173,17 +173,17 @@ export const updatePackageConfigHandler: RequestHandler< } }; -export const deletePackageConfigHandler: RequestHandler< +export const deletePackagePolicyHandler: RequestHandler< unknown, unknown, - TypeOf + TypeOf > = async (context, request, response) => { const soClient = context.core.savedObjects.client; const user = (await appContextService.getSecurity()?.authc.getCurrentUser(request)) || undefined; try { - const body: DeletePackageConfigsResponse = await packageConfigService.delete( + const body: DeletePackagePoliciesResponse = await packagePolicyService.delete( soClient, - request.body.packageConfigIds, + request.body.packagePolicyIds, { user } ); return response.ok({ diff --git a/x-pack/plugins/ingest_manager/server/routes/package_policy/index.ts b/x-pack/plugins/ingest_manager/server/routes/package_policy/index.ts new file mode 100644 index 00000000000000..e571896ebe82de --- /dev/null +++ b/x-pack/plugins/ingest_manager/server/routes/package_policy/index.ts @@ -0,0 +1,73 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { IRouter } from 'src/core/server'; +import { PLUGIN_ID, PACKAGE_POLICY_API_ROUTES } from '../../constants'; +import { + GetPackagePoliciesRequestSchema, + GetOnePackagePolicyRequestSchema, + CreatePackagePolicyRequestSchema, + UpdatePackagePolicyRequestSchema, + DeletePackagePoliciesRequestSchema, +} from '../../types'; +import { + getPackagePoliciesHandler, + getOnePackagePolicyHandler, + createPackagePolicyHandler, + updatePackagePolicyHandler, + deletePackagePolicyHandler, +} from './handlers'; + +export const registerRoutes = (router: IRouter) => { + // List + router.get( + { + path: PACKAGE_POLICY_API_ROUTES.LIST_PATTERN, + validate: GetPackagePoliciesRequestSchema, + options: { tags: [`access:${PLUGIN_ID}-read`] }, + }, + getPackagePoliciesHandler + ); + + // Get one + router.get( + { + path: PACKAGE_POLICY_API_ROUTES.INFO_PATTERN, + validate: GetOnePackagePolicyRequestSchema, + options: { tags: [`access:${PLUGIN_ID}-read`] }, + }, + getOnePackagePolicyHandler + ); + + // Create + router.post( + { + path: PACKAGE_POLICY_API_ROUTES.CREATE_PATTERN, + validate: CreatePackagePolicyRequestSchema, + options: { tags: [`access:${PLUGIN_ID}-all`] }, + }, + createPackagePolicyHandler + ); + + // Update + router.put( + { + path: PACKAGE_POLICY_API_ROUTES.UPDATE_PATTERN, + validate: UpdatePackagePolicyRequestSchema, + options: { tags: [`access:${PLUGIN_ID}-all`] }, + }, + updatePackagePolicyHandler + ); + + // Delete + router.post( + { + path: PACKAGE_POLICY_API_ROUTES.DELETE_PATTERN, + validate: DeletePackagePoliciesRequestSchema, + options: { tags: [`access:${PLUGIN_ID}`] }, + }, + deletePackagePolicyHandler + ); +}; diff --git a/x-pack/plugins/ingest_manager/server/saved_objects/index.ts b/x-pack/plugins/ingest_manager/server/saved_objects/index.ts index eca2711363c854..50957c48f70e61 100644 --- a/x-pack/plugins/ingest_manager/server/saved_objects/index.ts +++ b/x-pack/plugins/ingest_manager/server/saved_objects/index.ts @@ -8,8 +8,8 @@ import { SavedObjectsServiceSetup, SavedObjectsType } from 'kibana/server'; import { EncryptedSavedObjectsPluginSetup } from '../../../encrypted_saved_objects/server'; import { OUTPUT_SAVED_OBJECT_TYPE, - AGENT_CONFIG_SAVED_OBJECT_TYPE, - PACKAGE_CONFIG_SAVED_OBJECT_TYPE, + AGENT_POLICY_SAVED_OBJECT_TYPE, + PACKAGE_POLICY_SAVED_OBJECT_TYPE, PACKAGES_SAVED_OBJECT_TYPE, AGENT_SAVED_OBJECT_TYPE, AGENT_EVENT_SAVED_OBJECT_TYPE, @@ -17,6 +17,13 @@ import { ENROLLMENT_API_KEYS_SAVED_OBJECT_TYPE, GLOBAL_SETTINGS_SAVED_OBJECT_TYPE, } from '../constants'; +import { + migrateAgentToV7100, + migrateAgentEventToV7100, + migrateAgentPolicyToV7100, + migrateEnrollmentApiKeysToV7100, + migratePackagePolicyToV7100, +} from './migrations/to_v7_10_0'; /* * Saved object types and mappings @@ -61,11 +68,11 @@ const savedObjectTypes: { [key: string]: SavedObjectsType } = { version: { type: 'keyword' }, user_provided_metadata: { type: 'flattened' }, local_metadata: { type: 'flattened' }, - config_id: { type: 'keyword' }, + policy_id: { type: 'keyword' }, + policy_revision: { type: 'integer' }, last_updated: { type: 'date' }, last_checkin: { type: 'date' }, last_checkin_status: { type: 'keyword' }, - config_revision: { type: 'integer' }, default_api_key_id: { type: 'keyword' }, default_api_key: { type: 'binary' }, updated_at: { type: 'date' }, @@ -73,6 +80,9 @@ const savedObjectTypes: { [key: string]: SavedObjectsType } = { packages: { type: 'keyword' }, }, }, + migrations: { + '7.10.0': migrateAgentToV7100, + }, }, [AGENT_ACTION_SAVED_OBJECT_TYPE]: { name: AGENT_ACTION_SAVED_OBJECT_TYPE, @@ -104,7 +114,7 @@ const savedObjectTypes: { [key: string]: SavedObjectsType } = { subtype: { type: 'keyword' }, agent_id: { type: 'keyword' }, action_id: { type: 'keyword' }, - config_id: { type: 'keyword' }, + policy_id: { type: 'keyword' }, stream_id: { type: 'keyword' }, timestamp: { type: 'date' }, message: { type: 'text' }, @@ -112,9 +122,12 @@ const savedObjectTypes: { [key: string]: SavedObjectsType } = { data: { type: 'text' }, }, }, + migrations: { + '7.10.0': migrateAgentEventToV7100, + }, }, - [AGENT_CONFIG_SAVED_OBJECT_TYPE]: { - name: AGENT_CONFIG_SAVED_OBJECT_TYPE, + [AGENT_POLICY_SAVED_OBJECT_TYPE]: { + name: AGENT_POLICY_SAVED_OBJECT_TYPE, hidden: false, namespaceType: 'agnostic', management: { @@ -127,13 +140,16 @@ const savedObjectTypes: { [key: string]: SavedObjectsType } = { namespace: { type: 'keyword' }, is_default: { type: 'boolean' }, status: { type: 'keyword' }, - package_configs: { type: 'keyword' }, + package_policies: { type: 'keyword' }, updated_at: { type: 'date' }, updated_by: { type: 'keyword' }, revision: { type: 'integer' }, monitoring_enabled: { type: 'keyword', index: false }, }, }, + migrations: { + '7.10.0': migrateAgentPolicyToV7100, + }, }, [ENROLLMENT_API_KEYS_SAVED_OBJECT_TYPE]: { name: ENROLLMENT_API_KEYS_SAVED_OBJECT_TYPE, @@ -148,13 +164,16 @@ const savedObjectTypes: { [key: string]: SavedObjectsType } = { type: { type: 'keyword' }, api_key: { type: 'binary' }, api_key_id: { type: 'keyword' }, - config_id: { type: 'keyword' }, + policy_id: { type: 'keyword' }, created_at: { type: 'date' }, updated_at: { type: 'date' }, expire_at: { type: 'date' }, active: { type: 'boolean' }, }, }, + migrations: { + '7.10.0': migrateEnrollmentApiKeysToV7100, + }, }, [OUTPUT_SAVED_OBJECT_TYPE]: { name: OUTPUT_SAVED_OBJECT_TYPE, @@ -176,8 +195,8 @@ const savedObjectTypes: { [key: string]: SavedObjectsType } = { }, }, }, - [PACKAGE_CONFIG_SAVED_OBJECT_TYPE]: { - name: PACKAGE_CONFIG_SAVED_OBJECT_TYPE, + [PACKAGE_POLICY_SAVED_OBJECT_TYPE]: { + name: PACKAGE_POLICY_SAVED_OBJECT_TYPE, hidden: false, namespaceType: 'agnostic', management: { @@ -189,7 +208,7 @@ const savedObjectTypes: { [key: string]: SavedObjectsType } = { description: { type: 'text' }, namespace: { type: 'keyword' }, enabled: { type: 'boolean' }, - config_id: { type: 'keyword' }, + policy_id: { type: 'keyword' }, output_id: { type: 'keyword' }, package: { properties: { @@ -231,6 +250,9 @@ const savedObjectTypes: { [key: string]: SavedObjectsType } = { created_by: { type: 'keyword' }, }, }, + migrations: { + '7.10.0': migratePackagePolicyToV7100, + }, }, [PACKAGES_SAVED_OBJECT_TYPE]: { name: PACKAGES_SAVED_OBJECT_TYPE, @@ -285,7 +307,7 @@ export function registerEncryptedSavedObjects( 'name', 'type', 'api_key_id', - 'config_id', + 'policy_id', 'created_at', 'updated_at', 'expire_at', @@ -316,12 +338,11 @@ export function registerEncryptedSavedObjects( 'version', 'user_provided_metadata', 'local_metadata', - 'config_id', + 'policy_id', + 'policy_revision', 'last_updated', 'last_checkin', 'last_checkin_status', - 'config_revision', - 'config_newest_revision', 'updated_at', 'current_error_events', 'unenrolled_at', diff --git a/x-pack/plugins/ingest_manager/server/saved_objects/migrations/to_v7_10_0.ts b/x-pack/plugins/ingest_manager/server/saved_objects/migrations/to_v7_10_0.ts new file mode 100644 index 00000000000000..f45b69eaaa79c2 --- /dev/null +++ b/x-pack/plugins/ingest_manager/server/saved_objects/migrations/to_v7_10_0.ts @@ -0,0 +1,72 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { SavedObjectMigrationFn } from 'kibana/server'; +import { Agent, AgentEvent, AgentPolicy, PackagePolicy, EnrollmentAPIKey } from '../../types'; + +export const migrateAgentToV7100: SavedObjectMigrationFn< + Exclude & { + config_id?: string; + config_revision?: number | null; + }, + Agent +> = (agentDoc) => { + agentDoc.attributes.policy_id = agentDoc.attributes.config_id; + delete agentDoc.attributes.config_id; + + agentDoc.attributes.policy_revision = agentDoc.attributes.config_revision; + delete agentDoc.attributes.config_revision; + + return agentDoc; +}; + +export const migrateAgentEventToV7100: SavedObjectMigrationFn< + Exclude & { + config_id?: string; + }, + AgentEvent +> = (agentEventDoc) => { + agentEventDoc.attributes.policy_id = agentEventDoc.attributes.config_id; + delete agentEventDoc.attributes.config_id; + + return agentEventDoc; +}; + +export const migrateAgentPolicyToV7100: SavedObjectMigrationFn< + Exclude & { + package_configs: string[] | PackagePolicy[]; + }, + AgentPolicy +> = (agentPolicyDoc) => { + agentPolicyDoc.attributes.package_policies = agentPolicyDoc.attributes.package_configs; + delete agentPolicyDoc.attributes.package_configs; + + return agentPolicyDoc; +}; + +export const migrateEnrollmentApiKeysToV7100: SavedObjectMigrationFn< + Exclude & { + config_id?: string; + }, + EnrollmentAPIKey +> = (enrollmentApiKeyDoc) => { + enrollmentApiKeyDoc.attributes.policy_id = enrollmentApiKeyDoc.attributes.config_id; + delete enrollmentApiKeyDoc.attributes.config_id; + + return enrollmentApiKeyDoc; +}; + +export const migratePackagePolicyToV7100: SavedObjectMigrationFn< + Exclude & { + config_id: string; + }, + PackagePolicy +> = (packagePolicyDoc) => { + packagePolicyDoc.attributes.policy_id = packagePolicyDoc.attributes.config_id; + delete packagePolicyDoc.attributes.config_id; + + return packagePolicyDoc; +}; diff --git a/x-pack/plugins/ingest_manager/server/services/agent_config.ts b/x-pack/plugins/ingest_manager/server/services/agent_config.ts deleted file mode 100644 index 10b5d9aa0b2f8b..00000000000000 --- a/x-pack/plugins/ingest_manager/server/services/agent_config.ts +++ /dev/null @@ -1,442 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -import { uniq } from 'lodash'; -import { SavedObjectsClientContract } from 'src/core/server'; -import { AuthenticatedUser } from '../../../security/server'; -import { - DEFAULT_AGENT_CONFIG, - AGENT_CONFIG_SAVED_OBJECT_TYPE, - AGENT_SAVED_OBJECT_TYPE, -} from '../constants'; -import { - PackageConfig, - NewAgentConfig, - AgentConfig, - AgentConfigSOAttributes, - FullAgentConfig, - AgentConfigStatus, - ListWithKuery, -} from '../types'; -import { DeleteAgentConfigResponse, storedPackageConfigsToAgentInputs } from '../../common'; -import { listAgents } from './agents'; -import { packageConfigService } from './package_config'; -import { outputService } from './output'; -import { agentConfigUpdateEventHandler } from './agent_config_update'; - -const SAVED_OBJECT_TYPE = AGENT_CONFIG_SAVED_OBJECT_TYPE; - -class AgentConfigService { - private triggerAgentConfigUpdatedEvent = async ( - soClient: SavedObjectsClientContract, - action: string, - agentConfigId: string - ) => { - return agentConfigUpdateEventHandler(soClient, action, agentConfigId); - }; - - private async _update( - soClient: SavedObjectsClientContract, - id: string, - agentConfig: Partial, - user?: AuthenticatedUser, - options: { bumpRevision: boolean } = { bumpRevision: true } - ): Promise { - const oldAgentConfig = await this.get(soClient, id, false); - - if (!oldAgentConfig) { - throw new Error('Agent config not found'); - } - - if ( - oldAgentConfig.status === AgentConfigStatus.Inactive && - agentConfig.status !== AgentConfigStatus.Active - ) { - throw new Error( - `Agent config ${id} cannot be updated because it is ${oldAgentConfig.status}` - ); - } - - await soClient.update(SAVED_OBJECT_TYPE, id, { - ...agentConfig, - ...(options.bumpRevision ? { revision: oldAgentConfig.revision + 1 } : {}), - updated_at: new Date().toISOString(), - updated_by: user ? user.username : 'system', - }); - - return (await this.get(soClient, id)) as AgentConfig; - } - - public async ensureDefaultAgentConfig(soClient: SavedObjectsClientContract) { - const configs = await soClient.find({ - type: AGENT_CONFIG_SAVED_OBJECT_TYPE, - searchFields: ['is_default'], - search: 'true', - }); - - if (configs.total === 0) { - const newDefaultAgentConfig: NewAgentConfig = { - ...DEFAULT_AGENT_CONFIG, - }; - - return this.create(soClient, newDefaultAgentConfig); - } - - return { - id: configs.saved_objects[0].id, - ...configs.saved_objects[0].attributes, - }; - } - - public async create( - soClient: SavedObjectsClientContract, - agentConfig: NewAgentConfig, - options?: { id?: string; user?: AuthenticatedUser } - ): Promise { - const newSo = await soClient.create( - SAVED_OBJECT_TYPE, - { - ...agentConfig, - revision: 1, - updated_at: new Date().toISOString(), - updated_by: options?.user?.username || 'system', - } as AgentConfig, - options - ); - - if (!agentConfig.is_default) { - await this.triggerAgentConfigUpdatedEvent(soClient, 'created', newSo.id); - } - - return { id: newSo.id, ...newSo.attributes }; - } - - public async get( - soClient: SavedObjectsClientContract, - id: string, - withPackageConfigs: boolean = true - ): Promise { - const agentConfigSO = await soClient.get(SAVED_OBJECT_TYPE, id); - if (!agentConfigSO) { - return null; - } - - if (agentConfigSO.error) { - throw new Error(agentConfigSO.error.message); - } - - const agentConfig = { id: agentConfigSO.id, ...agentConfigSO.attributes }; - - if (withPackageConfigs) { - agentConfig.package_configs = - (await packageConfigService.getByIDs( - soClient, - (agentConfigSO.attributes.package_configs as string[]) || [] - )) || []; - } - - return agentConfig; - } - - public async list( - soClient: SavedObjectsClientContract, - options: ListWithKuery & { - withPackageConfigs?: boolean; - } - ): Promise<{ items: AgentConfig[]; total: number; page: number; perPage: number }> { - const { - page = 1, - perPage = 20, - sortField = 'updated_at', - sortOrder = 'desc', - kuery, - withPackageConfigs = false, - } = options; - - const agentConfigsSO = await soClient.find({ - type: SAVED_OBJECT_TYPE, - sortField, - sortOrder, - page, - perPage, - // To ensure users don't need to know about SO data structure... - filter: kuery - ? kuery.replace( - new RegExp(`${SAVED_OBJECT_TYPE}\.`, 'g'), - `${SAVED_OBJECT_TYPE}.attributes.` - ) - : undefined, - }); - - const agentConfigs = await Promise.all( - agentConfigsSO.saved_objects.map(async (agentConfigSO) => { - const agentConfig = { - id: agentConfigSO.id, - ...agentConfigSO.attributes, - }; - if (withPackageConfigs) { - const agentConfigWithPackageConfigs = await this.get( - soClient, - agentConfigSO.id, - withPackageConfigs - ); - if (agentConfigWithPackageConfigs) { - agentConfig.package_configs = agentConfigWithPackageConfigs.package_configs; - } - } - return agentConfig; - }) - ); - - return { - items: agentConfigs, - total: agentConfigsSO.total, - page, - perPage, - }; - } - - public async update( - soClient: SavedObjectsClientContract, - id: string, - agentConfig: Partial, - options?: { user?: AuthenticatedUser } - ): Promise { - return this._update(soClient, id, agentConfig, options?.user); - } - - public async copy( - soClient: SavedObjectsClientContract, - id: string, - newAgentConfigProps: Pick, - options?: { user?: AuthenticatedUser } - ): Promise { - // Copy base config - const baseAgentConfig = await this.get(soClient, id, true); - if (!baseAgentConfig) { - throw new Error('Agent config not found'); - } - // eslint-disable-next-line @typescript-eslint/naming-convention - const { namespace, monitoring_enabled } = baseAgentConfig; - const newAgentConfig = await this.create( - soClient, - { - namespace, - monitoring_enabled, - ...newAgentConfigProps, - }, - options - ); - - // Copy all package configs - if (baseAgentConfig.package_configs.length) { - const newPackageConfigs = (baseAgentConfig.package_configs as PackageConfig[]).map( - (packageConfig: PackageConfig) => { - const { id: packageConfigId, version, ...newPackageConfig } = packageConfig; - return newPackageConfig; - } - ); - await packageConfigService.bulkCreate(soClient, newPackageConfigs, newAgentConfig.id, { - ...options, - bumpConfigRevision: false, - }); - } - - // Get updated config - const updatedAgentConfig = await this.get(soClient, newAgentConfig.id, true); - if (!updatedAgentConfig) { - throw new Error('Copied agent config not found'); - } - - return updatedAgentConfig; - } - - public async bumpRevision( - soClient: SavedObjectsClientContract, - id: string, - options?: { user?: AuthenticatedUser } - ): Promise { - return this._update(soClient, id, {}, options?.user); - } - - public async assignPackageConfigs( - soClient: SavedObjectsClientContract, - id: string, - packageConfigIds: string[], - options: { user?: AuthenticatedUser; bumpRevision: boolean } = { bumpRevision: true } - ): Promise { - const oldAgentConfig = await this.get(soClient, id, false); - - if (!oldAgentConfig) { - throw new Error('Agent config not found'); - } - - return await this._update( - soClient, - id, - { - package_configs: uniq( - [...((oldAgentConfig.package_configs || []) as string[])].concat(packageConfigIds) - ), - }, - options?.user, - { bumpRevision: options.bumpRevision } - ); - } - - public async unassignPackageConfigs( - soClient: SavedObjectsClientContract, - id: string, - packageConfigIds: string[], - options?: { user?: AuthenticatedUser } - ): Promise { - const oldAgentConfig = await this.get(soClient, id, false); - - if (!oldAgentConfig) { - throw new Error('Agent config not found'); - } - - return await this._update( - soClient, - id, - { - package_configs: uniq( - [...((oldAgentConfig.package_configs || []) as string[])].filter( - (pkgConfigId) => !packageConfigIds.includes(pkgConfigId) - ) - ), - }, - options?.user - ); - } - - public async getDefaultAgentConfigId(soClient: SavedObjectsClientContract) { - const configs = await soClient.find({ - type: AGENT_CONFIG_SAVED_OBJECT_TYPE, - searchFields: ['is_default'], - search: 'true', - }); - - if (configs.saved_objects.length === 0) { - throw new Error('No default agent config'); - } - - return configs.saved_objects[0].id; - } - - public async delete( - soClient: SavedObjectsClientContract, - id: string - ): Promise { - const config = await this.get(soClient, id, false); - if (!config) { - throw new Error('Agent configuration not found'); - } - - const { id: defaultConfigId } = await this.ensureDefaultAgentConfig(soClient); - if (id === defaultConfigId) { - throw new Error('The default agent configuration cannot be deleted'); - } - - const { total } = await listAgents(soClient, { - showInactive: false, - perPage: 0, - page: 1, - kuery: `${AGENT_SAVED_OBJECT_TYPE}.config_id:${id}`, - }); - - if (total > 0) { - throw new Error('Cannot delete agent config that is assigned to agent(s)'); - } - - if (config.package_configs && config.package_configs.length) { - await packageConfigService.delete(soClient, config.package_configs as string[], { - skipUnassignFromAgentConfigs: true, - }); - } - await soClient.delete(SAVED_OBJECT_TYPE, id); - await this.triggerAgentConfigUpdatedEvent(soClient, 'deleted', id); - return { - id, - success: true, - }; - } - - public async getFullConfig( - soClient: SavedObjectsClientContract, - id: string, - options?: { standalone: boolean } - ): Promise { - let config; - - try { - config = await this.get(soClient, id); - } catch (err) { - if (!err.isBoom || err.output.statusCode !== 404) { - throw err; - } - } - - if (!config) { - return null; - } - - const defaultOutputId = await outputService.getDefaultOutputId(soClient); - if (!defaultOutputId) { - throw new Error('Default output is not setup'); - } - const defaultOutput = await outputService.get(soClient, defaultOutputId); - - const agentConfig: FullAgentConfig = { - id: config.id, - outputs: { - // TEMPORARY as we only support a default output - ...[defaultOutput].reduce( - // eslint-disable-next-line @typescript-eslint/naming-convention - (outputs, { config: outputConfig, name, type, hosts, ca_sha256, api_key }) => { - outputs[name] = { - type, - hosts, - ca_sha256, - api_key, - ...outputConfig, - }; - - if (options?.standalone) { - delete outputs[name].api_key; - outputs[name].username = 'ES_USERNAME'; - outputs[name].password = 'ES_PASSWORD'; - } - - return outputs; - }, - {} as FullAgentConfig['outputs'] - ), - }, - inputs: storedPackageConfigsToAgentInputs(config.package_configs as PackageConfig[]), - revision: config.revision, - ...(config.monitoring_enabled && config.monitoring_enabled.length > 0 - ? { - agent: { - monitoring: { - use_output: defaultOutput.name, - enabled: true, - logs: config.monitoring_enabled.indexOf('logs') >= 0, - metrics: config.monitoring_enabled.indexOf('metrics') >= 0, - }, - }, - } - : { - agent: { - monitoring: { enabled: false, logs: false, metrics: false }, - }, - }), - }; - - return agentConfig; - } -} - -export const agentConfigService = new AgentConfigService(); diff --git a/x-pack/plugins/ingest_manager/server/services/agent_config.test.ts b/x-pack/plugins/ingest_manager/server/services/agent_policy.test.ts similarity index 74% rename from x-pack/plugins/ingest_manager/server/services/agent_config.test.ts rename to x-pack/plugins/ingest_manager/server/services/agent_policy.test.ts index 225251b061e58d..dc2a89c661ac3d 100644 --- a/x-pack/plugins/ingest_manager/server/services/agent_config.test.ts +++ b/x-pack/plugins/ingest_manager/server/services/agent_policy.test.ts @@ -5,10 +5,10 @@ */ import { savedObjectsClientMock } from 'src/core/server/mocks'; -import { agentConfigService } from './agent_config'; +import { agentPolicyService } from './agent_policy'; import { Output } from '../types'; -function getSavedObjectMock(configAttributes: any) { +function getSavedObjectMock(agentPolicyAttributes: any) { const mock = savedObjectsClientMock.create(); mock.get.mockImplementation(async (type: string, id: string) => { @@ -16,7 +16,7 @@ function getSavedObjectMock(configAttributes: any) { type, id, references: [], - attributes: configAttributes, + attributes: agentPolicyAttributes, }; }); @@ -41,16 +41,16 @@ jest.mock('./output', () => { }; }); -describe('agent config', () => { - describe('getFullConfig', () => { - it('should return a config without monitoring if not monitoring is not enabled', async () => { +describe('agent policy', () => { + describe('getFullAgentPolicy', () => { + it('should return a policy without monitoring if not monitoring is not enabled', async () => { const soClient = getSavedObjectMock({ revision: 1, }); - const config = await agentConfigService.getFullConfig(soClient, 'config'); + const agentPolicy = await agentPolicyService.getFullAgentPolicy(soClient, 'agent-policy'); - expect(config).toMatchObject({ - id: 'config', + expect(agentPolicy).toMatchObject({ + id: 'agent-policy', outputs: { default: { type: 'elasticsearch', @@ -71,15 +71,15 @@ describe('agent config', () => { }); }); - it('should return a config with monitoring if monitoring is enabled for logs', async () => { + it('should return a policy with monitoring if monitoring is enabled for logs', async () => { const soClient = getSavedObjectMock({ revision: 1, monitoring_enabled: ['logs'], }); - const config = await agentConfigService.getFullConfig(soClient, 'config'); + const agentPolicy = await agentPolicyService.getFullAgentPolicy(soClient, 'agent-policy'); - expect(config).toMatchObject({ - id: 'config', + expect(agentPolicy).toMatchObject({ + id: 'agent-policy', outputs: { default: { type: 'elasticsearch', @@ -101,15 +101,15 @@ describe('agent config', () => { }); }); - it('should return a config with monitoring if monitoring is enabled for metrics', async () => { + it('should return a policy with monitoring if monitoring is enabled for metrics', async () => { const soClient = getSavedObjectMock({ revision: 1, monitoring_enabled: ['metrics'], }); - const config = await agentConfigService.getFullConfig(soClient, 'config'); + const agentPolicy = await agentPolicyService.getFullAgentPolicy(soClient, 'agent-policy'); - expect(config).toMatchObject({ - id: 'config', + expect(agentPolicy).toMatchObject({ + id: 'agent-policy', outputs: { default: { type: 'elasticsearch', diff --git a/x-pack/plugins/ingest_manager/server/services/agent_policy.ts b/x-pack/plugins/ingest_manager/server/services/agent_policy.ts new file mode 100644 index 00000000000000..21bc7b021e83a2 --- /dev/null +++ b/x-pack/plugins/ingest_manager/server/services/agent_policy.ts @@ -0,0 +1,442 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { uniq } from 'lodash'; +import { SavedObjectsClientContract } from 'src/core/server'; +import { AuthenticatedUser } from '../../../security/server'; +import { + DEFAULT_AGENT_POLICY, + AGENT_POLICY_SAVED_OBJECT_TYPE, + AGENT_SAVED_OBJECT_TYPE, +} from '../constants'; +import { + PackagePolicy, + NewAgentPolicy, + AgentPolicy, + AgentPolicySOAttributes, + FullAgentPolicy, + AgentPolicyStatus, + ListWithKuery, +} from '../types'; +import { DeleteAgentPolicyResponse, storedPackagePoliciesToAgentInputs } from '../../common'; +import { listAgents } from './agents'; +import { packagePolicyService } from './package_policy'; +import { outputService } from './output'; +import { agentPolicyUpdateEventHandler } from './agent_policy_update'; + +const SAVED_OBJECT_TYPE = AGENT_POLICY_SAVED_OBJECT_TYPE; + +class AgentPolicyService { + private triggerAgentPolicyUpdatedEvent = async ( + soClient: SavedObjectsClientContract, + action: string, + agentPolicyId: string + ) => { + return agentPolicyUpdateEventHandler(soClient, action, agentPolicyId); + }; + + private async _update( + soClient: SavedObjectsClientContract, + id: string, + agentPolicy: Partial, + user?: AuthenticatedUser, + options: { bumpRevision: boolean } = { bumpRevision: true } + ): Promise { + const oldAgentPolicy = await this.get(soClient, id, false); + + if (!oldAgentPolicy) { + throw new Error('Agent policy not found'); + } + + if ( + oldAgentPolicy.status === AgentPolicyStatus.Inactive && + agentPolicy.status !== AgentPolicyStatus.Active + ) { + throw new Error( + `Agent policy ${id} cannot be updated because it is ${oldAgentPolicy.status}` + ); + } + + await soClient.update(SAVED_OBJECT_TYPE, id, { + ...agentPolicy, + ...(options.bumpRevision ? { revision: oldAgentPolicy.revision + 1 } : {}), + updated_at: new Date().toISOString(), + updated_by: user ? user.username : 'system', + }); + + return (await this.get(soClient, id)) as AgentPolicy; + } + + public async ensureDefaultAgentPolicy(soClient: SavedObjectsClientContract) { + const agentPolicies = await soClient.find({ + type: AGENT_POLICY_SAVED_OBJECT_TYPE, + searchFields: ['is_default'], + search: 'true', + }); + + if (agentPolicies.total === 0) { + const newDefaultAgentPolicy: NewAgentPolicy = { + ...DEFAULT_AGENT_POLICY, + }; + + return this.create(soClient, newDefaultAgentPolicy); + } + + return { + id: agentPolicies.saved_objects[0].id, + ...agentPolicies.saved_objects[0].attributes, + }; + } + + public async create( + soClient: SavedObjectsClientContract, + agentPolicy: NewAgentPolicy, + options?: { id?: string; user?: AuthenticatedUser } + ): Promise { + const newSo = await soClient.create( + SAVED_OBJECT_TYPE, + { + ...agentPolicy, + revision: 1, + updated_at: new Date().toISOString(), + updated_by: options?.user?.username || 'system', + } as AgentPolicy, + options + ); + + if (!agentPolicy.is_default) { + await this.triggerAgentPolicyUpdatedEvent(soClient, 'created', newSo.id); + } + + return { id: newSo.id, ...newSo.attributes }; + } + + public async get( + soClient: SavedObjectsClientContract, + id: string, + withPackagePolicies: boolean = true + ): Promise { + const agentPolicySO = await soClient.get(SAVED_OBJECT_TYPE, id); + if (!agentPolicySO) { + return null; + } + + if (agentPolicySO.error) { + throw new Error(agentPolicySO.error.message); + } + + const agentPolicy = { id: agentPolicySO.id, ...agentPolicySO.attributes }; + + if (withPackagePolicies) { + agentPolicy.package_policies = + (await packagePolicyService.getByIDs( + soClient, + (agentPolicySO.attributes.package_policies as string[]) || [] + )) || []; + } + + return agentPolicy; + } + + public async list( + soClient: SavedObjectsClientContract, + options: ListWithKuery & { + withPackagePolicies?: boolean; + } + ): Promise<{ items: AgentPolicy[]; total: number; page: number; perPage: number }> { + const { + page = 1, + perPage = 20, + sortField = 'updated_at', + sortOrder = 'desc', + kuery, + withPackagePolicies = false, + } = options; + + const agentPoliciesSO = await soClient.find({ + type: SAVED_OBJECT_TYPE, + sortField, + sortOrder, + page, + perPage, + // To ensure users don't need to know about SO data structure... + filter: kuery + ? kuery.replace( + new RegExp(`${SAVED_OBJECT_TYPE}\.`, 'g'), + `${SAVED_OBJECT_TYPE}.attributes.` + ) + : undefined, + }); + + const agentPolicies = await Promise.all( + agentPoliciesSO.saved_objects.map(async (agentPolicySO) => { + const agentPolicy = { + id: agentPolicySO.id, + ...agentPolicySO.attributes, + }; + if (withPackagePolicies) { + const agentPolicyWithPackagePolicies = await this.get( + soClient, + agentPolicySO.id, + withPackagePolicies + ); + if (agentPolicyWithPackagePolicies) { + agentPolicy.package_policies = agentPolicyWithPackagePolicies.package_policies; + } + } + return agentPolicy; + }) + ); + + return { + items: agentPolicies, + total: agentPoliciesSO.total, + page, + perPage, + }; + } + + public async update( + soClient: SavedObjectsClientContract, + id: string, + agentPolicy: Partial, + options?: { user?: AuthenticatedUser } + ): Promise { + return this._update(soClient, id, agentPolicy, options?.user); + } + + public async copy( + soClient: SavedObjectsClientContract, + id: string, + newAgentPolicyProps: Pick, + options?: { user?: AuthenticatedUser } + ): Promise { + // Copy base agent policy + const baseAgentPolicy = await this.get(soClient, id, true); + if (!baseAgentPolicy) { + throw new Error('Agent policy not found'); + } + // eslint-disable-next-line @typescript-eslint/naming-convention + const { namespace, monitoring_enabled } = baseAgentPolicy; + const newAgentPolicy = await this.create( + soClient, + { + namespace, + monitoring_enabled, + ...newAgentPolicyProps, + }, + options + ); + + // Copy all package policies + if (baseAgentPolicy.package_policies.length) { + const newPackagePolicies = (baseAgentPolicy.package_policies as PackagePolicy[]).map( + (packagePolicy: PackagePolicy) => { + const { id: packagePolicyId, version, ...newPackagePolicy } = packagePolicy; + return newPackagePolicy; + } + ); + await packagePolicyService.bulkCreate(soClient, newPackagePolicies, newAgentPolicy.id, { + ...options, + bumpRevision: false, + }); + } + + // Get updated agent policy + const updatedAgentPolicy = await this.get(soClient, newAgentPolicy.id, true); + if (!updatedAgentPolicy) { + throw new Error('Copied agent policy not found'); + } + + return updatedAgentPolicy; + } + + public async bumpRevision( + soClient: SavedObjectsClientContract, + id: string, + options?: { user?: AuthenticatedUser } + ): Promise { + return this._update(soClient, id, {}, options?.user); + } + + public async assignPackagePolicies( + soClient: SavedObjectsClientContract, + id: string, + packagePolicyIds: string[], + options: { user?: AuthenticatedUser; bumpRevision: boolean } = { bumpRevision: true } + ): Promise { + const oldAgentPolicy = await this.get(soClient, id, false); + + if (!oldAgentPolicy) { + throw new Error('Agent policy not found'); + } + + return await this._update( + soClient, + id, + { + package_policies: uniq( + [...((oldAgentPolicy.package_policies || []) as string[])].concat(packagePolicyIds) + ), + }, + options?.user, + { bumpRevision: options.bumpRevision } + ); + } + + public async unassignPackagePolicies( + soClient: SavedObjectsClientContract, + id: string, + packagePolicyIds: string[], + options?: { user?: AuthenticatedUser } + ): Promise { + const oldAgentPolicy = await this.get(soClient, id, false); + + if (!oldAgentPolicy) { + throw new Error('Agent policy not found'); + } + + return await this._update( + soClient, + id, + { + package_policies: uniq( + [...((oldAgentPolicy.package_policies || []) as string[])].filter( + (packagePolicyId) => !packagePolicyIds.includes(packagePolicyId) + ) + ), + }, + options?.user + ); + } + + public async getDefaultAgentPolicyId(soClient: SavedObjectsClientContract) { + const agentPolicies = await soClient.find({ + type: AGENT_POLICY_SAVED_OBJECT_TYPE, + searchFields: ['is_default'], + search: 'true', + }); + + if (agentPolicies.saved_objects.length === 0) { + throw new Error('No default agent policy'); + } + + return agentPolicies.saved_objects[0].id; + } + + public async delete( + soClient: SavedObjectsClientContract, + id: string + ): Promise { + const agentPolicy = await this.get(soClient, id, false); + if (!agentPolicy) { + throw new Error('Agent policy not found'); + } + + const { id: defaultAgentPolicyId } = await this.ensureDefaultAgentPolicy(soClient); + if (id === defaultAgentPolicyId) { + throw new Error('The default agent policy cannot be deleted'); + } + + const { total } = await listAgents(soClient, { + showInactive: false, + perPage: 0, + page: 1, + kuery: `${AGENT_SAVED_OBJECT_TYPE}.policy_id:${id}`, + }); + + if (total > 0) { + throw new Error('Cannot delete agent policy that is assigned to agent(s)'); + } + + if (agentPolicy.package_policies && agentPolicy.package_policies.length) { + await packagePolicyService.delete(soClient, agentPolicy.package_policies as string[], { + skipUnassignFromAgentPolicies: true, + }); + } + await soClient.delete(SAVED_OBJECT_TYPE, id); + await this.triggerAgentPolicyUpdatedEvent(soClient, 'deleted', id); + return { + id, + success: true, + }; + } + + public async getFullAgentPolicy( + soClient: SavedObjectsClientContract, + id: string, + options?: { standalone: boolean } + ): Promise { + let agentPolicy; + + try { + agentPolicy = await this.get(soClient, id); + } catch (err) { + if (!err.isBoom || err.output.statusCode !== 404) { + throw err; + } + } + + if (!agentPolicy) { + return null; + } + + const defaultOutputId = await outputService.getDefaultOutputId(soClient); + if (!defaultOutputId) { + throw new Error('Default output is not setup'); + } + const defaultOutput = await outputService.get(soClient, defaultOutputId); + + const fullAgentPolicy: FullAgentPolicy = { + id: agentPolicy.id, + outputs: { + // TEMPORARY as we only support a default output + ...[defaultOutput].reduce( + // eslint-disable-next-line @typescript-eslint/naming-convention + (outputs, { config: outputConfig, name, type, hosts, ca_sha256, api_key }) => { + outputs[name] = { + type, + hosts, + ca_sha256, + api_key, + ...outputConfig, + }; + + if (options?.standalone) { + delete outputs[name].api_key; + outputs[name].username = 'ES_USERNAME'; + outputs[name].password = 'ES_PASSWORD'; + } + + return outputs; + }, + {} as FullAgentPolicy['outputs'] + ), + }, + inputs: storedPackagePoliciesToAgentInputs(agentPolicy.package_policies as PackagePolicy[]), + revision: agentPolicy.revision, + ...(agentPolicy.monitoring_enabled && agentPolicy.monitoring_enabled.length > 0 + ? { + agent: { + monitoring: { + use_output: defaultOutput.name, + enabled: true, + logs: agentPolicy.monitoring_enabled.indexOf('logs') >= 0, + metrics: agentPolicy.monitoring_enabled.indexOf('metrics') >= 0, + }, + }, + } + : { + agent: { + monitoring: { enabled: false, logs: false, metrics: false }, + }, + }), + }; + + return fullAgentPolicy; + } +} + +export const agentPolicyService = new AgentPolicyService(); diff --git a/x-pack/plugins/ingest_manager/server/services/agent_config_update.ts b/x-pack/plugins/ingest_manager/server/services/agent_policy_update.ts similarity index 64% rename from x-pack/plugins/ingest_manager/server/services/agent_config_update.ts rename to x-pack/plugins/ingest_manager/server/services/agent_policy_update.ts index 3d40d128afda8d..3c743dd957f62e 100644 --- a/x-pack/plugins/ingest_manager/server/services/agent_config_update.ts +++ b/x-pack/plugins/ingest_manager/server/services/agent_policy_update.ts @@ -5,14 +5,14 @@ */ import { SavedObjectsClientContract } from 'src/core/server'; -import { generateEnrollmentAPIKey, deleteEnrollmentApiKeyForConfigId } from './api_keys'; -import { unenrollForConfigId } from './agents'; +import { generateEnrollmentAPIKey, deleteEnrollmentApiKeyForAgentPolicyId } from './api_keys'; +import { unenrollForAgentPolicyId } from './agents'; import { outputService } from './output'; -export async function agentConfigUpdateEventHandler( +export async function agentPolicyUpdateEventHandler( soClient: SavedObjectsClientContract, action: string, - configId: string + agentPolicyId: string ) { const adminUser = await outputService.getAdminUser(soClient); // If no admin user fleet is not enabled just skip this hook @@ -22,12 +22,12 @@ export async function agentConfigUpdateEventHandler( if (action === 'created') { await generateEnrollmentAPIKey(soClient, { - configId, + agentPolicyId, }); } if (action === 'deleted') { - await unenrollForConfigId(soClient, configId); - await deleteEnrollmentApiKeyForConfigId(soClient, configId); + await unenrollForAgentPolicyId(soClient, agentPolicyId); + await deleteEnrollmentApiKeyForAgentPolicyId(soClient, agentPolicyId); } } diff --git a/x-pack/plugins/ingest_manager/server/services/agents/acks.test.ts b/x-pack/plugins/ingest_manager/server/services/agents/acks.test.ts index 6ea59c9a76a497..80fdc305d0ba7f 100644 --- a/x-pack/plugins/ingest_manager/server/services/agents/acks.test.ts +++ b/x-pack/plugins/ingest_manager/server/services/agents/acks.test.ts @@ -93,7 +93,7 @@ describe('test agent acks services', () => { ]); }); - it('should update config field on the agent if a config change is acknowledged', async () => { + it('should update config field on the agent if a policy change is acknowledged', async () => { const mockSavedObjectsClient = savedObjectsClientMock.create(); const mockStartEncryptedSOPlugin = encryptedSavedObjectsMock.createStart(); appContextService.start(({ @@ -117,7 +117,7 @@ describe('test agent acks services', () => { created_at: '2020-03-14T19:45:02.620Z', data: JSON.stringify({ config: { - id: 'config1', + id: 'policy1', revision: 4, settings: { monitoring: { @@ -207,7 +207,7 @@ describe('test agent acks services', () => { ({ id: 'id', type: AGENT_TYPE_PERMANENT, - config_id: 'config1', + policy_id: 'policy1', } as unknown) as Agent, [ { @@ -224,10 +224,10 @@ describe('test agent acks services', () => { expect(mockSavedObjectsClient.bulkUpdate.mock.calls[0][0][0]).toMatchInlineSnapshot(` Object { "attributes": Object { - "config_revision": 4, "packages": Array [ "system", ], + "policy_revision": 4, }, "id": "id", "type": "fleet-agents", @@ -235,7 +235,7 @@ describe('test agent acks services', () => { `); }); - it('should not update config field on the agent if a config change for an old revision is acknowledged', async () => { + it('should not update config field on the agent if a policy change for an old revision is acknowledged', async () => { const mockSavedObjectsClient = savedObjectsClientMock.create(); const mockStartEncryptedSOPlugin = encryptedSavedObjectsMock.createStart(); appContextService.start(({ @@ -259,7 +259,7 @@ describe('test agent acks services', () => { created_at: '2020-03-14T19:45:02.620Z', data: JSON.stringify({ config: { - id: 'config1', + id: 'policy1', revision: 4, settings: { monitoring: { @@ -349,8 +349,8 @@ describe('test agent acks services', () => { ({ id: 'id', type: AGENT_TYPE_PERMANENT, - config_id: 'config1', - config_revision: 100, + policy_id: 'policy1', + policy_revision: 100, } as unknown) as Agent, [ { diff --git a/x-pack/plugins/ingest_manager/server/services/agents/acks.ts b/x-pack/plugins/ingest_manager/server/services/agents/acks.ts index 1dfe4e067dafe8..87572ce405ee70 100644 --- a/x-pack/plugins/ingest_manager/server/services/agents/acks.ts +++ b/x-pack/plugins/ingest_manager/server/services/agents/acks.ts @@ -18,7 +18,7 @@ import { AgentEventSOAttributes, AgentSOAttributes, AgentActionSOAttributes, - FullAgentConfig, + FullAgentPolicy, } from '../../types'; import { AGENT_EVENT_SAVED_OBJECT_TYPE, @@ -70,35 +70,35 @@ export async function acknowledgeAgentActions( await forceUnenrollAgent(soClient, agent.id); } - const config = getLatestConfigIfUpdated(agent, actions); + const agentPolicy = getLatestAgentPolicyIfUpdated(agent, actions); await soClient.bulkUpdate([ - ...(config ? [buildUpdateAgentConfig(agent.id, config)] : []), + ...(agentPolicy ? [buildUpdateAgentPolicy(agent.id, agentPolicy)] : []), ...buildUpdateAgentActionSentAt(actionIds), ]); return actions; } -function getLatestConfigIfUpdated(agent: Agent, actions: AgentAction[]) { - return actions.reduce((acc, action) => { +function getLatestAgentPolicyIfUpdated(agent: Agent, actions: AgentAction[]) { + return actions.reduce((acc, action) => { if (action.type !== 'CONFIG_CHANGE') { return acc; } const data = action.data || {}; - if (data?.config?.id !== agent.config_id) { + if (data?.config?.id !== agent.policy_id) { return acc; } - const currentRevision = (acc && acc.revision) || agent.config_revision || 0; + const currentRevision = (acc && acc.revision) || agent.policy_revision || 0; return data?.config?.revision > currentRevision ? data?.config : acc; }, null); } -function buildUpdateAgentConfig(agentId: string, config: FullAgentConfig) { - const packages = config.inputs.reduce((acc, input) => { +function buildUpdateAgentPolicy(agentId: string, agentPolicy: FullAgentPolicy) { + const packages = agentPolicy.inputs.reduce((acc, input) => { const packageName = input.meta?.package?.name; if (packageName && acc.indexOf(packageName) < 0) { return [packageName, ...acc]; @@ -110,7 +110,7 @@ function buildUpdateAgentConfig(agentId: string, config: FullAgentConfig) { type: AGENT_SAVED_OBJECT_TYPE, id: agentId, attributes: { - config_revision: config.revision, + policy_revision: agentPolicy.revision, packages, }, }; diff --git a/x-pack/plugins/ingest_manager/server/services/agents/checkin/index.ts b/x-pack/plugins/ingest_manager/server/services/agents/checkin/index.ts index ece38f86b49870..78e6a11fa78a47 100644 --- a/x-pack/plugins/ingest_manager/server/services/agents/checkin/index.ts +++ b/x-pack/plugins/ingest_manager/server/services/agents/checkin/index.ts @@ -63,7 +63,7 @@ async function processEventsForCheckin( const updatedErrorEvents: Array = [...agent.current_error_events]; for (const event of events) { // @ts-ignore - event.config_id = agent.config_id; + event.policy_id = agent.policy_id; if (isErrorOrState(event)) { // Remove any global or specific to a stream event diff --git a/x-pack/plugins/ingest_manager/server/services/agents/checkin/state_new_actions.ts b/x-pack/plugins/ingest_manager/server/services/agents/checkin/state_new_actions.ts index 418b59e1ca2e96..e10d013fe84a96 100644 --- a/x-pack/plugins/ingest_manager/server/services/agents/checkin/state_new_actions.ts +++ b/x-pack/plugins/ingest_manager/server/services/agents/checkin/state_new_actions.ts @@ -20,16 +20,16 @@ import { Agent, AgentAction, AgentSOAttributes, - AgentConfig, - FullAgentConfig, + AgentPolicy, + FullAgentPolicy, } from '../../../types'; -import { agentConfigService } from '../../agent_config'; +import { agentPolicyService } from '../../agent_policy'; import * as APIKeysService from '../../api_keys'; import { AGENT_SAVED_OBJECT_TYPE, AGENT_UPDATE_ACTIONS_INTERVAL_MS, - AGENT_CONFIG_ROLLOUT_RATE_LIMIT_INTERVAL_MS, - AGENT_CONFIG_ROLLOUT_RATE_LIMIT_REQUEST_PER_INTERVAL, + AGENT_POLICY_ROLLOUT_RATE_LIMIT_INTERVAL_MS, + AGENT_POLICY_ROLLOUT_RATE_LIMIT_REQUEST_PER_INTERVAL, } from '../../../constants'; import { createAgentAction, getNewActionsSince } from '../actions'; import { appContextService } from '../../app_context'; @@ -54,14 +54,16 @@ function getInternalUserSOClient() { return appContextService.getInternalUserSOClient(fakeRequest); } -function createAgentConfigSharedObservable(configId: string) { +function createAgentPolicySharedObservable(agentPolicyId: string) { const internalSOClient = getInternalUserSOClient(); return timer(0, AGENT_UPDATE_ACTIONS_INTERVAL_MS).pipe( switchMap(() => - from(agentConfigService.get(internalSOClient, configId) as Promise) + from(agentPolicyService.get(internalSOClient, agentPolicyId) as Promise) ), distinctUntilKeyChanged('revision'), - switchMap((data) => from(agentConfigService.getFullConfig(internalSOClient, configId))), + switchMap((data) => + from(agentPolicyService.getFullAgentPolicy(internalSOClient, agentPolicyId)) + ), shareReplay({ refCount: true, bufferSize: 1 }) ); } @@ -100,50 +102,54 @@ async function getOrCreateAgentDefaultOutputAPIKey( return outputAPIKey.key; } -function shouldCreateAgentConfigAction(agent: Agent, config: FullAgentConfig | null): boolean { - if (!config || !config.revision) { +function shouldCreateAgentPolicyAction(agent: Agent, agentPolicy: FullAgentPolicy | null): boolean { + if (!agentPolicy || !agentPolicy.revision) { return false; } - const isAgentConfigOutdated = !agent.config_revision || agent.config_revision < config.revision; - if (!isAgentConfigOutdated) { + const isAgentPolicyOutdated = + !agent.policy_revision || agent.policy_revision < agentPolicy.revision; + if (!isAgentPolicyOutdated) { return false; } return true; } -async function createAgentActionFromConfig( +async function createAgentActionFromAgentPolicy( soClient: SavedObjectsClientContract, agent: Agent, - config: FullAgentConfig | null + policy: FullAgentPolicy | null ) { // Deep clone !not supporting Date, and undefined value. - const newConfig = JSON.parse(JSON.stringify(config)); + const newAgentPolicy = JSON.parse(JSON.stringify(policy)); - // Mutate the config to set the api token for this agent - newConfig.outputs.default.api_key = await getOrCreateAgentDefaultOutputAPIKey(soClient, agent); + // Mutate the policy to set the api token for this agent + newAgentPolicy.outputs.default.api_key = await getOrCreateAgentDefaultOutputAPIKey( + soClient, + agent + ); - const configChangeAction = await createAgentAction(soClient, { + const policyChangeAction = await createAgentAction(soClient, { agent_id: agent.id, type: 'CONFIG_CHANGE', - data: { config: newConfig } as any, + data: { config: newAgentPolicy } as any, created_at: new Date().toISOString(), sent_at: undefined, }); - return [configChangeAction]; + return [policyChangeAction]; } export function agentCheckinStateNewActionsFactory() { // Shared Observables - const agentConfigs$ = new Map>(); + const agentPolicies$ = new Map>(); const newActions$ = createNewActionsSharedObservable(); // Rx operators const rateLimiter = createRateLimiter( - appContextService.getConfig()?.fleet.agentConfigRolloutRateLimitIntervalMs ?? - AGENT_CONFIG_ROLLOUT_RATE_LIMIT_INTERVAL_MS, - appContextService.getConfig()?.fleet.agentConfigRolloutRateLimitRequestPerInterval ?? - AGENT_CONFIG_ROLLOUT_RATE_LIMIT_REQUEST_PER_INTERVAL + appContextService.getConfig()?.fleet.agentPolicyRolloutRateLimitIntervalMs ?? + AGENT_POLICY_ROLLOUT_RATE_LIMIT_INTERVAL_MS, + appContextService.getConfig()?.fleet.agentPolicyRolloutRateLimitRequestPerInterval ?? + AGENT_POLICY_ROLLOUT_RATE_LIMIT_REQUEST_PER_INTERVAL ); async function subscribeToNewActions( @@ -151,23 +157,23 @@ export function agentCheckinStateNewActionsFactory() { agent: Agent, options?: { signal: AbortSignal } ): Promise { - if (!agent.config_id) { - throw new Error('Agent do not have a config'); + if (!agent.policy_id) { + throw new Error('Agent does not have a policy'); } - const configId = agent.config_id; - if (!agentConfigs$.has(configId)) { - agentConfigs$.set(configId, createAgentConfigSharedObservable(configId)); + const agentPolicyId = agent.policy_id; + if (!agentPolicies$.has(agentPolicyId)) { + agentPolicies$.set(agentPolicyId, createAgentPolicySharedObservable(agentPolicyId)); } - const agentConfig$ = agentConfigs$.get(configId); - if (!agentConfig$) { - throw new Error(`Invalid state no observable for config ${configId}`); + const agentPolicy$ = agentPolicies$.get(agentPolicyId); + if (!agentPolicy$) { + throw new Error(`Invalid state, no observable for policy ${agentPolicyId}`); } - const stream$ = agentConfig$.pipe( + const stream$ = agentPolicy$.pipe( timeout(appContextService.getConfig()?.fleet.pollingRequestTimeout || 0), - filter((config) => shouldCreateAgentConfigAction(agent, config)), + filter((agentPolicy) => shouldCreateAgentPolicyAction(agent, agentPolicy)), rateLimiter(), - mergeMap((config) => createAgentActionFromConfig(soClient, agent, config)), + mergeMap((agentPolicy) => createAgentActionFromAgentPolicy(soClient, agent, agentPolicy)), merge(newActions$), mergeMap(async (data) => { if (!data) { diff --git a/x-pack/plugins/ingest_manager/server/services/agents/enroll.ts b/x-pack/plugins/ingest_manager/server/services/agents/enroll.ts index b63b1c13e4df9d..606d5c4dcbb90a 100644 --- a/x-pack/plugins/ingest_manager/server/services/agents/enroll.ts +++ b/x-pack/plugins/ingest_manager/server/services/agents/enroll.ts @@ -16,7 +16,7 @@ import { appContextService } from '../app_context'; export async function enroll( soClient: SavedObjectsClientContract, type: AgentType, - configId: string, + agentPolicyId: string, metadata?: { local: any; userProvided: any }, sharedId?: string ): Promise { @@ -33,7 +33,7 @@ export async function enroll( const agentData: AgentSOAttributes = { shared_id: sharedId, active: true, - config_id: configId, + policy_id: agentPolicyId, type, enrolled_at: enrolledAt, user_provided_metadata: metadata?.userProvided ?? {}, @@ -64,7 +64,7 @@ export async function enroll( ); } - const accessAPIKey = await APIKeyService.generateAccessApiKey(soClient, agent.id, configId); + const accessAPIKey = await APIKeyService.generateAccessApiKey(soClient, agent.id); await soClient.update(AGENT_SAVED_OBJECT_TYPE, agent.id, { access_api_key_id: accessAPIKey.id, diff --git a/x-pack/plugins/ingest_manager/server/services/agents/reassign.ts b/x-pack/plugins/ingest_manager/server/services/agents/reassign.ts index ecc2c987d04b66..3075e146093e37 100644 --- a/x-pack/plugins/ingest_manager/server/services/agents/reassign.ts +++ b/x-pack/plugins/ingest_manager/server/services/agents/reassign.ts @@ -8,20 +8,20 @@ import { SavedObjectsClientContract } from 'kibana/server'; import Boom from 'boom'; import { AGENT_SAVED_OBJECT_TYPE } from '../../constants'; import { AgentSOAttributes } from '../../types'; -import { agentConfigService } from '../agent_config'; +import { agentPolicyService } from '../agent_policy'; export async function reassignAgent( soClient: SavedObjectsClientContract, agentId: string, - newConfigId: string + newAgentPolicyId: string ) { - const config = await agentConfigService.get(soClient, newConfigId); - if (!config) { - throw Boom.notFound(`Agent Configuration not found: ${newConfigId}`); + const agentPolicy = await agentPolicyService.get(soClient, newAgentPolicyId); + if (!agentPolicy) { + throw Boom.notFound(`Agent policy not found: ${newAgentPolicyId}`); } await soClient.update(AGENT_SAVED_OBJECT_TYPE, agentId, { - config_id: newConfigId, - config_revision: null, + policy_id: newAgentPolicyId, + policy_revision: null, }); } diff --git a/x-pack/plugins/ingest_manager/server/services/agents/status.ts b/x-pack/plugins/ingest_manager/server/services/agents/status.ts index 86336714a511ee..35033cbe86ea51 100644 --- a/x-pack/plugins/ingest_manager/server/services/agents/status.ts +++ b/x-pack/plugins/ingest_manager/server/services/agents/status.ts @@ -21,9 +21,9 @@ export async function getAgentStatusById( export const getAgentStatus = AgentStatusKueryHelper.getAgentStatus; -export async function getAgentStatusForConfig( +export async function getAgentStatusForAgentPolicy( soClient: SavedObjectsClientContract, - configId?: string + agentPolicyId?: string ) { const [all, online, error, offline] = await Promise.all( [ @@ -36,17 +36,17 @@ export async function getAgentStatusForConfig( showInactive: false, perPage: 0, page: 1, - kuery: configId + kuery: agentPolicyId ? kuery - ? `(${kuery}) and (${AGENT_SAVED_OBJECT_TYPE}.config_id:"${configId}")` - : `${AGENT_SAVED_OBJECT_TYPE}.config_id:"${configId}"` + ? `(${kuery}) and (${AGENT_SAVED_OBJECT_TYPE}.policy_id:"${agentPolicyId}")` + : `${AGENT_SAVED_OBJECT_TYPE}.policy_id:"${agentPolicyId}"` : kuery, }) ) ); return { - events: await getEventsCount(soClient, configId), + events: await getEventsCount(soClient, agentPolicyId), total: all.total, online: online.total, error: error.total, @@ -55,11 +55,11 @@ export async function getAgentStatusForConfig( }; } -async function getEventsCount(soClient: SavedObjectsClientContract, configId?: string) { +async function getEventsCount(soClient: SavedObjectsClientContract, agentPolicyId?: string) { const { total } = await soClient.find({ type: AGENT_EVENT_SAVED_OBJECT_TYPE, - searchFields: ['config_id'], - search: configId, + searchFields: ['policy_id'], + search: agentPolicyId, perPage: 0, page: 1, sortField: 'timestamp', diff --git a/x-pack/plugins/ingest_manager/server/services/agents/update.ts b/x-pack/plugins/ingest_manager/server/services/agents/update.ts index 11ad76fe81784a..b85a831294b58c 100644 --- a/x-pack/plugins/ingest_manager/server/services/agents/update.ts +++ b/x-pack/plugins/ingest_manager/server/services/agents/update.ts @@ -9,12 +9,15 @@ import { listAgents } from './crud'; import { AGENT_SAVED_OBJECT_TYPE } from '../../constants'; import { unenrollAgent } from './unenroll'; -export async function unenrollForConfigId(soClient: SavedObjectsClientContract, configId: string) { +export async function unenrollForAgentPolicyId( + soClient: SavedObjectsClientContract, + policyId: string +) { let hasMore = true; let page = 1; while (hasMore) { const { agents } = await listAgents(soClient, { - kuery: `${AGENT_SAVED_OBJECT_TYPE}.config_id:"${configId}"`, + kuery: `${AGENT_SAVED_OBJECT_TYPE}.policy_id:"${policyId}"`, page: page++, perPage: 1000, showInactive: true, diff --git a/x-pack/plugins/ingest_manager/server/services/api_keys/enrollment_api_key.ts b/x-pack/plugins/ingest_manager/server/services/api_keys/enrollment_api_key.ts index e1266ac5941642..f058166fc2a4fa 100644 --- a/x-pack/plugins/ingest_manager/server/services/api_keys/enrollment_api_key.ts +++ b/x-pack/plugins/ingest_manager/server/services/api_keys/enrollment_api_key.ts @@ -10,7 +10,7 @@ import { SavedObjectsClientContract, SavedObject } from 'src/core/server'; import { EnrollmentAPIKey, EnrollmentAPIKeySOAttributes } from '../../types'; import { ENROLLMENT_API_KEYS_SAVED_OBJECT_TYPE } from '../../constants'; import { createAPIKey, invalidateAPIKey } from './security'; -import { agentConfigService } from '../agent_config'; +import { agentPolicyService } from '../agent_policy'; import { appContextService } from '../app_context'; export async function listEnrollmentApiKeys( @@ -75,9 +75,9 @@ export async function deleteEnrollmentApiKey(soClient: SavedObjectsClientContrac }); } -export async function deleteEnrollmentApiKeyForConfigId( +export async function deleteEnrollmentApiKeyForAgentPolicyId( soClient: SavedObjectsClientContract, - configId: string + agentPolicyId: string ) { let hasMore = true; let page = 1; @@ -85,7 +85,7 @@ export async function deleteEnrollmentApiKeyForConfigId( const { items } = await listEnrollmentApiKeys(soClient, { page: page++, perPage: 100, - kuery: `${ENROLLMENT_API_KEYS_SAVED_OBJECT_TYPE}.config_id:${configId}`, + kuery: `${ENROLLMENT_API_KEYS_SAVED_OBJECT_TYPE}.policy_id:${agentPolicyId}`, }); if (items.length === 0) { @@ -103,15 +103,16 @@ export async function generateEnrollmentAPIKey( data: { name?: string; expiration?: string; - configId?: string; + agentPolicyId?: string; } ) { const id = uuid.v4(); const { name: providedKeyName } = data; - if (data.configId) { - await validateConfigId(soClient, data.configId); + if (data.agentPolicyId) { + await validateAgentPolicyId(soClient, data.agentPolicyId); } - const configId = data.configId ?? (await agentConfigService.getDefaultAgentConfigId(soClient)); + const agentPolicyId = + data.agentPolicyId ?? (await agentPolicyService.getDefaultAgentPolicyId(soClient)); const name = providedKeyName ? `${providedKeyName} (${id})` : id; const key = await createAPIKey(soClient, name, { // Useless role to avoid to have the privilege of the user that created the key @@ -140,7 +141,7 @@ export async function generateEnrollmentAPIKey( api_key_id: key.id, api_key: apiKey, name, - config_id: configId, + policy_id: agentPolicyId, created_at: new Date().toISOString(), } ); @@ -148,12 +149,12 @@ export async function generateEnrollmentAPIKey( return getEnrollmentAPIKey(soClient, so.id); } -async function validateConfigId(soClient: SavedObjectsClientContract, configId: string) { +async function validateAgentPolicyId(soClient: SavedObjectsClientContract, agentPolicyId: string) { try { - await agentConfigService.get(soClient, configId); + await agentPolicyService.get(soClient, agentPolicyId); } catch (e) { if (e.isBoom && e.output.statusCode === 404) { - throw Boom.badRequest(`Agent config ${configId} does not exist`); + throw Boom.badRequest(`Agent policy ${agentPolicyId} does not exist`); } throw e; } diff --git a/x-pack/plugins/ingest_manager/server/services/api_keys/index.ts b/x-pack/plugins/ingest_manager/server/services/api_keys/index.ts index 9e8f1fac4e02bf..2e0ccdbcfdca60 100644 --- a/x-pack/plugins/ingest_manager/server/services/api_keys/index.ts +++ b/x-pack/plugins/ingest_manager/server/services/api_keys/index.ts @@ -38,11 +38,7 @@ export async function generateOutputApiKey( return { key: `${key.id}:${key.api_key}`, id: key.id }; } -export async function generateAccessApiKey( - soClient: SavedObjectsClientContract, - agentId: string, - configId: string -) { +export async function generateAccessApiKey(soClient: SavedObjectsClientContract, agentId: string) { const key = await createAPIKey(soClient, agentId, { // Useless role to avoid to have the privilege of the user that created the key 'fleet-apikey-access': { diff --git a/x-pack/plugins/ingest_manager/server/services/config.ts b/x-pack/plugins/ingest_manager/server/services/config.ts index 9043b1cc634a0d..23cd38cc123cef 100644 --- a/x-pack/plugins/ingest_manager/server/services/config.ts +++ b/x-pack/plugins/ingest_manager/server/services/config.ts @@ -7,7 +7,7 @@ import { Observable, Subscription } from 'rxjs'; import { IngestManagerConfigType } from '../'; /** - * Kibana config observable service, *NOT* agent config + * Kibana config observable service, *NOT* agent policy */ class ConfigService { private observable: Observable | null = null; diff --git a/x-pack/plugins/ingest_manager/server/services/epm/agent/agent.ts b/x-pack/plugins/ingest_manager/server/services/epm/agent/agent.ts index 88c54d213554cb..eeadac6e168b1f 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/agent/agent.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/agent/agent.ts @@ -6,11 +6,11 @@ import Handlebars from 'handlebars'; import { safeLoad, safeDump } from 'js-yaml'; -import { PackageConfigConfigRecord } from '../../../../common'; +import { PackagePolicyConfigRecord } from '../../../../common'; const handlebars = Handlebars.create(); -export function createStream(variables: PackageConfigConfigRecord, streamTemplate: string) { +export function createStream(variables: PackagePolicyConfigRecord, streamTemplate: string) { const { vars, yamlValues } = buildTemplateVariables(variables, streamTemplate); const template = handlebars.compile(streamTemplate, { noEscape: true }); @@ -54,7 +54,7 @@ function replaceVariablesInYaml(yamlVariables: { [k: string]: any }, yaml: any) return yaml; } -function buildTemplateVariables(variables: PackageConfigConfigRecord, streamTemplate: string) { +function buildTemplateVariables(variables: PackagePolicyConfigRecord, streamTemplate: string) { const yamlValues: { [k: string]: any } = {}; const vars = Object.entries(variables).reduce((acc, [key, recordEntry]) => { // support variables with . like key.patterns diff --git a/x-pack/plugins/ingest_manager/server/services/epm/packages/get.ts b/x-pack/plugins/ingest_manager/server/services/epm/packages/get.ts index 7093723806ea39..1688900fc1758f 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/packages/get.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/packages/get.ts @@ -50,7 +50,7 @@ export async function getPackages( return packageList; } -// Get package names for packages which cannot have more than one package config on an agent config +// Get package names for packages which cannot have more than one package policy on an agent policy // Assume packages only export one config template for now export async function getLimitedPackages(options: { savedObjectsClient: SavedObjectsClientContract; diff --git a/x-pack/plugins/ingest_manager/server/services/epm/packages/remove.ts b/x-pack/plugins/ingest_manager/server/services/epm/packages/remove.ts index 1e50c67d63c422..bc71ead34c3d4d 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/packages/remove.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/packages/remove.ts @@ -6,13 +6,13 @@ import { SavedObjectsClientContract } from 'src/core/server'; import Boom from 'boom'; -import { PACKAGES_SAVED_OBJECT_TYPE, PACKAGE_CONFIG_SAVED_OBJECT_TYPE } from '../../../constants'; +import { PACKAGES_SAVED_OBJECT_TYPE, PACKAGE_POLICY_SAVED_OBJECT_TYPE } from '../../../constants'; import { AssetReference, AssetType, ElasticsearchAssetType } from '../../../types'; import { CallESAsCurrentUser } from '../../../types'; import { getInstallation, savedObjectTypes } from './index'; import { deletePipeline } from '../elasticsearch/ingest_pipeline/'; import { installIndexPatterns } from '../kibana/index_pattern/install'; -import { packageConfigService, appContextService } from '../..'; +import { packagePolicyService, appContextService } from '../..'; import { splitPkgKey } from '../registry'; export async function removeInstallation(options: { @@ -28,15 +28,15 @@ export async function removeInstallation(options: { if (installation.removable === false) throw Boom.badRequest(`${pkgName} is installed by default and cannot be removed`); - const { total } = await packageConfigService.list(savedObjectsClient, { - kuery: `${PACKAGE_CONFIG_SAVED_OBJECT_TYPE}.package.name:${pkgName}`, + const { total } = await packagePolicyService.list(savedObjectsClient, { + kuery: `${PACKAGE_POLICY_SAVED_OBJECT_TYPE}.package.name:${pkgName}`, page: 0, perPage: 0, }); if (total > 0) throw Boom.badRequest( - `unable to remove package with existing package config(s) in use by agent(s)` + `unable to remove package with existing package policy(s) in use by agent(s)` ); // recreate or delete index patterns when a package is uninstalled diff --git a/x-pack/plugins/ingest_manager/server/services/index.ts b/x-pack/plugins/ingest_manager/server/services/index.ts index f6ca9e7bbbe71f..e768862d2dee15 100644 --- a/x-pack/plugins/ingest_manager/server/services/index.ts +++ b/x-pack/plugins/ingest_manager/server/services/index.ts @@ -61,8 +61,8 @@ export interface AgentService { } // Saved object services -export { agentConfigService } from './agent_config'; -export { packageConfigService } from './package_config'; +export { agentPolicyService } from './agent_policy'; +export { packagePolicyService } from './package_policy'; export { outputService } from './output'; export { settingsService }; diff --git a/x-pack/plugins/ingest_manager/server/services/package_config.test.ts b/x-pack/plugins/ingest_manager/server/services/package_policy.test.ts similarity index 88% rename from x-pack/plugins/ingest_manager/server/services/package_config.test.ts rename to x-pack/plugins/ingest_manager/server/services/package_policy.test.ts index 28aa0d773d75b7..0d89c529576327 100644 --- a/x-pack/plugins/ingest_manager/server/services/package_config.test.ts +++ b/x-pack/plugins/ingest_manager/server/services/package_policy.test.ts @@ -5,9 +5,9 @@ */ import { savedObjectsClientMock } from 'src/core/server/mocks'; -import { createPackageConfigMock } from '../../common/mocks'; -import { packageConfigService } from './package_config'; -import { PackageInfo, PackageConfigSOAttributes } from '../types'; +import { createPackagePolicyMock } from '../../common/mocks'; +import { packagePolicyService } from './package_policy'; +import { PackageInfo, PackagePolicySOAttributes } from '../types'; import { SavedObjectsUpdateResponse } from 'src/core/server'; async function mockedGetAssetsData(_a: any, _b: any, dataset: string) { @@ -40,10 +40,10 @@ jest.mock('./epm/registry', () => { }; }); -describe('Package config service', () => { +describe('Package policy service', () => { describe('assignPackageStream', () => { it('should work with config variables from the stream', async () => { - const inputs = await packageConfigService.assignPackageStream( + const inputs = await packagePolicyService.assignPackageStream( ({ datasets: [ { @@ -104,7 +104,7 @@ describe('Package config service', () => { }); it('should work with config variables at the input level', async () => { - const inputs = await packageConfigService.assignPackageStream( + const inputs = await packagePolicyService.assignPackageStream( ({ datasets: [ { @@ -173,21 +173,21 @@ describe('Package config service', () => { type: 'abcd', references: [], version: 'test', - attributes: createPackageConfigMock(), + attributes: createPackagePolicyMock(), }); savedObjectsClient.update.mockImplementation( async ( type: string, id: string - ): Promise> => { + ): Promise> => { throw savedObjectsClient.errors.createConflictError('abc', '123'); } ); await expect( - packageConfigService.update( + packagePolicyService.update( savedObjectsClient, - 'the-package-config-id', - createPackageConfigMock() + 'the-package-policy-id', + createPackagePolicyMock() ) ).rejects.toThrow('Saved object [abc/123] conflict'); }); diff --git a/x-pack/plugins/ingest_manager/server/services/package_config.ts b/x-pack/plugins/ingest_manager/server/services/package_policy.ts similarity index 58% rename from x-pack/plugins/ingest_manager/server/services/package_config.ts rename to x-pack/plugins/ingest_manager/server/services/package_policy.ts index 665c08316588c0..b7e1806979db82 100644 --- a/x-pack/plugins/ingest_manager/server/services/package_config.ts +++ b/x-pack/plugins/ingest_manager/server/services/package_policy.ts @@ -6,92 +6,92 @@ import { SavedObjectsClientContract } from 'src/core/server'; import { AuthenticatedUser } from '../../../security/server'; import { - DeletePackageConfigsResponse, - PackageConfigInput, - PackageConfigInputStream, + DeletePackagePoliciesResponse, + PackagePolicyInput, + PackagePolicyInputStream, PackageInfo, ListWithKuery, - packageToPackageConfig, + packageToPackagePolicy, isPackageLimited, - doesAgentConfigAlreadyIncludePackage, + doesAgentPolicyAlreadyIncludePackage, } from '../../common'; -import { PACKAGE_CONFIG_SAVED_OBJECT_TYPE } from '../constants'; +import { PACKAGE_POLICY_SAVED_OBJECT_TYPE } from '../constants'; import { - NewPackageConfig, - UpdatePackageConfig, - PackageConfig, - PackageConfigSOAttributes, + NewPackagePolicy, + UpdatePackagePolicy, + PackagePolicy, + PackagePolicySOAttributes, RegistryPackage, CallESAsCurrentUser, } from '../types'; -import { agentConfigService } from './agent_config'; +import { agentPolicyService } from './agent_policy'; import { outputService } from './output'; import * as Registry from './epm/registry'; import { getPackageInfo, getInstallation, ensureInstalledPackage } from './epm/packages'; import { getAssetsData } from './epm/packages/assets'; import { createStream } from './epm/agent/agent'; -const SAVED_OBJECT_TYPE = PACKAGE_CONFIG_SAVED_OBJECT_TYPE; +const SAVED_OBJECT_TYPE = PACKAGE_POLICY_SAVED_OBJECT_TYPE; function getDataset(st: string) { return st.split('.')[1]; } -class PackageConfigService { +class PackagePolicyService { public async create( soClient: SavedObjectsClientContract, callCluster: CallESAsCurrentUser, - packageConfig: NewPackageConfig, - options?: { id?: string; user?: AuthenticatedUser; bumpConfigRevision?: boolean } - ): Promise { - // Check that its agent config does not have a package config with the same name - const parentAgentConfig = await agentConfigService.get(soClient, packageConfig.config_id); - if (!parentAgentConfig) { - throw new Error('Agent config not found'); + packagePolicy: NewPackagePolicy, + options?: { id?: string; user?: AuthenticatedUser; bumpRevision?: boolean } + ): Promise { + // Check that its agent policy does not have a package policy with the same name + const parentAgentPolicy = await agentPolicyService.get(soClient, packagePolicy.policy_id); + if (!parentAgentPolicy) { + throw new Error('Agent policy not found'); } else { if ( - (parentAgentConfig.package_configs as PackageConfig[]).find( - (siblingPackageConfig) => siblingPackageConfig.name === packageConfig.name + (parentAgentPolicy.package_policies as PackagePolicy[]).find( + (siblingPackagePolicy) => siblingPackagePolicy.name === packagePolicy.name ) ) { - throw new Error('There is already a package with the same name on this agent config'); + throw new Error('There is already a package with the same name on this agent policy'); } } // Make sure the associated package is installed - if (packageConfig.package?.name) { + if (packagePolicy.package?.name) { const [, pkgInfo] = await Promise.all([ ensureInstalledPackage({ savedObjectsClient: soClient, - pkgName: packageConfig.package.name, + pkgName: packagePolicy.package.name, callCluster, }), getPackageInfo({ savedObjectsClient: soClient, - pkgName: packageConfig.package.name, - pkgVersion: packageConfig.package.version, + pkgName: packagePolicy.package.name, + pkgVersion: packagePolicy.package.version, }), ]); - // Check if it is a limited package, and if so, check that the corresponding agent config does not - // already contain a package config for this package + // Check if it is a limited package, and if so, check that the corresponding agent policy does not + // already contain a package policy for this package if (isPackageLimited(pkgInfo)) { - const agentConfig = await agentConfigService.get(soClient, packageConfig.config_id, true); - if (agentConfig && doesAgentConfigAlreadyIncludePackage(agentConfig, pkgInfo.name)) { + const agentPolicy = await agentPolicyService.get(soClient, packagePolicy.policy_id, true); + if (agentPolicy && doesAgentPolicyAlreadyIncludePackage(agentPolicy, pkgInfo.name)) { throw new Error( - `Unable to create package config. Package '${pkgInfo.name}' already exists on this agent config.` + `Unable to create package policy. Package '${pkgInfo.name}' already exists on this agent policy.` ); } } - packageConfig.inputs = await this.assignPackageStream(pkgInfo, packageConfig.inputs); + packagePolicy.inputs = await this.assignPackageStream(pkgInfo, packagePolicy.inputs); } const isoDate = new Date().toISOString(); - const newSo = await soClient.create( + const newSo = await soClient.create( SAVED_OBJECT_TYPE, { - ...packageConfig, + ...packagePolicy, revision: 1, created_at: isoDate, created_by: options?.user?.username ?? 'system', @@ -101,10 +101,10 @@ class PackageConfigService { options ); - // Assign it to the given agent config - await agentConfigService.assignPackageConfigs(soClient, packageConfig.config_id, [newSo.id], { + // Assign it to the given agent policy + await agentPolicyService.assignPackagePolicies(soClient, packagePolicy.policy_id, [newSo.id], { user: options?.user, - bumpRevision: options?.bumpConfigRevision ?? true, + bumpRevision: options?.bumpRevision ?? true, }); return { @@ -116,18 +116,18 @@ class PackageConfigService { public async bulkCreate( soClient: SavedObjectsClientContract, - packageConfigs: NewPackageConfig[], - configId: string, - options?: { user?: AuthenticatedUser; bumpConfigRevision?: boolean } - ): Promise { + packagePolicies: NewPackagePolicy[], + agentPolicyId: string, + options?: { user?: AuthenticatedUser; bumpRevision?: boolean } + ): Promise { const isoDate = new Date().toISOString(); // eslint-disable-next-line @typescript-eslint/naming-convention - const { saved_objects } = await soClient.bulkCreate( - packageConfigs.map((packageConfig) => ({ + const { saved_objects } = await soClient.bulkCreate( + packagePolicies.map((packagePolicy) => ({ type: SAVED_OBJECT_TYPE, attributes: { - ...packageConfig, - config_id: configId, + ...packagePolicy, + policy_id: agentPolicyId, revision: 1, created_at: isoDate, created_by: options?.user?.username ?? 'system', @@ -140,14 +140,14 @@ class PackageConfigService { // Filter out invalid SOs const newSos = saved_objects.filter((so) => !so.error && so.attributes); - // Assign it to the given agent config - await agentConfigService.assignPackageConfigs( + // Assign it to the given agent policy + await agentPolicyService.assignPackagePolicies( soClient, - configId, + agentPolicyId, newSos.map((newSo) => newSo.id), { user: options?.user, - bumpRevision: options?.bumpConfigRevision ?? true, + bumpRevision: options?.bumpRevision ?? true, } ); @@ -161,38 +161,38 @@ class PackageConfigService { public async get( soClient: SavedObjectsClientContract, id: string - ): Promise { - const packageConfigSO = await soClient.get(SAVED_OBJECT_TYPE, id); - if (!packageConfigSO) { + ): Promise { + const packagePolicySO = await soClient.get(SAVED_OBJECT_TYPE, id); + if (!packagePolicySO) { return null; } - if (packageConfigSO.error) { - throw new Error(packageConfigSO.error.message); + if (packagePolicySO.error) { + throw new Error(packagePolicySO.error.message); } return { - id: packageConfigSO.id, - version: packageConfigSO.version, - ...packageConfigSO.attributes, + id: packagePolicySO.id, + version: packagePolicySO.version, + ...packagePolicySO.attributes, }; } public async getByIDs( soClient: SavedObjectsClientContract, ids: string[] - ): Promise { - const packageConfigSO = await soClient.bulkGet( + ): Promise { + const packagePolicySO = await soClient.bulkGet( ids.map((id) => ({ id, type: SAVED_OBJECT_TYPE, })) ); - if (!packageConfigSO) { + if (!packagePolicySO) { return null; } - return packageConfigSO.saved_objects.map((so) => ({ + return packagePolicySO.saved_objects.map((so) => ({ id: so.id, version: so.version, ...so.attributes, @@ -202,10 +202,10 @@ class PackageConfigService { public async list( soClient: SavedObjectsClientContract, options: ListWithKuery - ): Promise<{ items: PackageConfig[]; total: number; page: number; perPage: number }> { + ): Promise<{ items: PackagePolicy[]; total: number; page: number; perPage: number }> { const { page = 1, perPage = 20, sortField = 'updated_at', sortOrder = 'desc', kuery } = options; - const packageConfigs = await soClient.find({ + const packagePolicies = await soClient.find({ type: SAVED_OBJECT_TYPE, sortField, sortOrder, @@ -221,12 +221,12 @@ class PackageConfigService { }); return { - items: packageConfigs.saved_objects.map((packageConfigSO) => ({ - id: packageConfigSO.id, - version: packageConfigSO.version, - ...packageConfigSO.attributes, + items: packagePolicies.saved_objects.map((packagePolicySO) => ({ + id: packagePolicySO.id, + version: packagePolicySO.version, + ...packagePolicySO.attributes, })), - total: packageConfigs.total, + total: packagePolicies.total, page, perPage, }; @@ -235,37 +235,37 @@ class PackageConfigService { public async update( soClient: SavedObjectsClientContract, id: string, - packageConfig: UpdatePackageConfig, + packagePolicy: UpdatePackagePolicy, options?: { user?: AuthenticatedUser } - ): Promise { - const oldPackageConfig = await this.get(soClient, id); - const { version, ...restOfPackageConfig } = packageConfig; + ): Promise { + const oldPackagePolicy = await this.get(soClient, id); + const { version, ...restOfPackagePolicy } = packagePolicy; - if (!oldPackageConfig) { - throw new Error('Package config not found'); + if (!oldPackagePolicy) { + throw new Error('Package policy not found'); } - // Check that its agent config does not have a package config with the same name - const parentAgentConfig = await agentConfigService.get(soClient, packageConfig.config_id); - if (!parentAgentConfig) { - throw new Error('Agent config not found'); + // Check that its agent policy does not have a package policy with the same name + const parentAgentPolicy = await agentPolicyService.get(soClient, packagePolicy.policy_id); + if (!parentAgentPolicy) { + throw new Error('Agent policy not found'); } else { if ( - (parentAgentConfig.package_configs as PackageConfig[]).find( - (siblingPackageConfig) => - siblingPackageConfig.id !== id && siblingPackageConfig.name === packageConfig.name + (parentAgentPolicy.package_policies as PackagePolicy[]).find( + (siblingPackagePolicy) => + siblingPackagePolicy.id !== id && siblingPackagePolicy.name === packagePolicy.name ) ) { - throw new Error('There is already a package with the same name on this agent config'); + throw new Error('There is already a package with the same name on this agent policy'); } } - await soClient.update( + await soClient.update( SAVED_OBJECT_TYPE, id, { - ...restOfPackageConfig, - revision: oldPackageConfig.revision + 1, + ...restOfPackagePolicy, + revision: oldPackagePolicy.revision + 1, updated_at: new Date().toISOString(), updated_by: options?.user?.username ?? 'system', }, @@ -274,32 +274,32 @@ class PackageConfigService { } ); - // Bump revision of associated agent config - await agentConfigService.bumpRevision(soClient, packageConfig.config_id, { + // Bump revision of associated agent policy + await agentPolicyService.bumpRevision(soClient, packagePolicy.policy_id, { user: options?.user, }); - return (await this.get(soClient, id)) as PackageConfig; + return (await this.get(soClient, id)) as PackagePolicy; } public async delete( soClient: SavedObjectsClientContract, ids: string[], - options?: { user?: AuthenticatedUser; skipUnassignFromAgentConfigs?: boolean } - ): Promise { - const result: DeletePackageConfigsResponse = []; + options?: { user?: AuthenticatedUser; skipUnassignFromAgentPolicies?: boolean } + ): Promise { + const result: DeletePackagePoliciesResponse = []; for (const id of ids) { try { - const oldPackageConfig = await this.get(soClient, id); - if (!oldPackageConfig) { - throw new Error('Package config not found'); + const oldPackagePolicy = await this.get(soClient, id); + if (!oldPackagePolicy) { + throw new Error('Package policy not found'); } - if (!options?.skipUnassignFromAgentConfigs) { - await agentConfigService.unassignPackageConfigs( + if (!options?.skipUnassignFromAgentPolicies) { + await agentPolicyService.unassignPackagePolicies( soClient, - oldPackageConfig.config_id, - [oldPackageConfig.id], + oldPackagePolicy.policy_id, + [oldPackagePolicy.id], { user: options?.user, } @@ -321,10 +321,10 @@ class PackageConfigService { return result; } - public async buildPackageConfigFromPackage( + public async buildPackagePolicyFromPackage( soClient: SavedObjectsClientContract, pkgName: string - ): Promise { + ): Promise { const pkgInstall = await getInstallation({ savedObjectsClient: soClient, pkgName }); if (pkgInstall) { const [pkgInfo, defaultOutputId] = await Promise.all([ @@ -339,15 +339,15 @@ class PackageConfigService { if (!defaultOutputId) { throw new Error('Default output is not set'); } - return packageToPackageConfig(pkgInfo, '', defaultOutputId); + return packageToPackagePolicy(pkgInfo, '', defaultOutputId); } } } public async assignPackageStream( pkgInfo: PackageInfo, - inputs: PackageConfigInput[] - ): Promise { + inputs: PackagePolicyInput[] + ): Promise { const registryPkgInfo = await Registry.fetchInfo(pkgInfo.name, pkgInfo.version); const inputsPromises = inputs.map((input) => _assignPackageStreamToInput(registryPkgInfo, pkgInfo, input) @@ -360,7 +360,7 @@ class PackageConfigService { async function _assignPackageStreamToInput( registryPkgInfo: RegistryPackage, pkgInfo: PackageInfo, - input: PackageConfigInput + input: PackagePolicyInput ) { const streamsPromises = input.streams.map((stream) => _assignPackageStreamToStream(registryPkgInfo, pkgInfo, input, stream) @@ -373,8 +373,8 @@ async function _assignPackageStreamToInput( async function _assignPackageStreamToStream( registryPkgInfo: RegistryPackage, pkgInfo: PackageInfo, - input: PackageConfigInput, - stream: PackageConfigInputStream + input: PackagePolicyInput, + stream: PackagePolicyInputStream ) { if (!stream.enabled) { return { ...stream, compiled_stream: undefined }; @@ -426,5 +426,5 @@ async function _assignPackageStreamToStream( return { ...stream }; } -export type PackageConfigServiceInterface = PackageConfigService; -export const packageConfigService = new PackageConfigService(); +export type PackagePolicyServiceInterface = PackagePolicyService; +export const packagePolicyService = new PackagePolicyService(); diff --git a/x-pack/plugins/ingest_manager/server/services/setup.ts b/x-pack/plugins/ingest_manager/server/services/setup.ts index 4ef093d38879ab..727b49cebc6080 100644 --- a/x-pack/plugins/ingest_manager/server/services/setup.ts +++ b/x-pack/plugins/ingest_manager/server/services/setup.ts @@ -8,21 +8,21 @@ import url from 'url'; import uuid from 'uuid'; import { SavedObjectsClientContract } from 'src/core/server'; import { CallESAsCurrentUser } from '../types'; -import { agentConfigService } from './agent_config'; +import { agentPolicyService } from './agent_policy'; import { outputService } from './output'; import { ensureInstalledDefaultPackages } from './epm/packages/install'; import { ensureDefaultIndices } from './epm/kibana/index_pattern/install'; import { - packageToPackageConfig, - PackageConfig, - AgentConfig, + packageToPackagePolicy, + PackagePolicy, + AgentPolicy, Installation, Output, - DEFAULT_AGENT_CONFIGS_PACKAGES, + DEFAULT_AGENT_POLICIES_PACKAGES, decodeCloudId, } from '../../common'; import { getPackageInfo } from './epm/packages'; -import { packageConfigService } from './package_config'; +import { packagePolicyService } from './package_policy'; import { generateEnrollmentAPIKey } from './api_keys'; import { settingsService } from '.'; import { appContextService } from './app_context'; @@ -51,11 +51,11 @@ export async function setupIngestManager( }); } try { - const [installedPackages, defaultOutput, config] = await Promise.all([ + const [installedPackages, defaultOutput, defaultAgentPolicy] = await Promise.all([ // packages installed by default ensureInstalledDefaultPackages(soClient, callCluster), outputService.ensureDefaultOutput(soClient), - agentConfigService.ensureDefaultAgentConfig(soClient), + agentPolicyService.ensureDefaultAgentPolicy(soClient), ensureDefaultIndices(callCluster), settingsService.getSettings(soClient).catch((e: any) => { if (e.isBoom && e.output.statusCode === 404) { @@ -86,36 +86,40 @@ export async function setupIngestManager( ]); // ensure default packages are added to the default conifg - const configWithPackageConfigs = await agentConfigService.get(soClient, config.id, true); - if (!configWithPackageConfigs) { - throw new Error('Config not found'); + const agentPolicyWithPackagePolicies = await agentPolicyService.get( + soClient, + defaultAgentPolicy.id, + true + ); + if (!agentPolicyWithPackagePolicies) { + throw new Error('Policy not found'); } if ( - configWithPackageConfigs.package_configs.length && - typeof configWithPackageConfigs.package_configs[0] === 'string' + agentPolicyWithPackagePolicies.package_policies.length && + typeof agentPolicyWithPackagePolicies.package_policies[0] === 'string' ) { - throw new Error('Config not found'); + throw new Error('Policy not found'); } for (const installedPackage of installedPackages) { - const packageShouldBeInstalled = DEFAULT_AGENT_CONFIGS_PACKAGES.some( + const packageShouldBeInstalled = DEFAULT_AGENT_POLICIES_PACKAGES.some( (packageName) => installedPackage.name === packageName ); if (!packageShouldBeInstalled) { continue; } - const isInstalled = configWithPackageConfigs.package_configs.some( - (d: PackageConfig | string) => { + const isInstalled = agentPolicyWithPackagePolicies.package_policies.some( + (d: PackagePolicy | string) => { return typeof d !== 'string' && d.package?.name === installedPackage.name; } ); if (!isInstalled) { - await addPackageToConfig( + await addPackageToAgentPolicy( soClient, callCluster, installedPackage, - configWithPackageConfigs, + agentPolicyWithPackagePolicies, defaultOutput ); } @@ -185,15 +189,15 @@ export async function setupFleet( fleet_enroll_password: password, }); - const { items: agentConfigs } = await agentConfigService.list(soClient, { + const { items: agentPolicies } = await agentPolicyService.list(soClient, { perPage: 10000, }); await Promise.all( - agentConfigs.map((agentConfig) => { + agentPolicies.map((agentPolicy) => { return generateEnrollmentAPIKey(soClient, { name: `Default`, - configId: agentConfig.id, + agentPolicyId: agentPolicy.id, }); }) ); @@ -203,11 +207,11 @@ function generateRandomPassword() { return Buffer.from(uuid.v4()).toString('base64'); } -async function addPackageToConfig( +async function addPackageToAgentPolicy( soClient: SavedObjectsClientContract, callCluster: CallESAsCurrentUser, packageToInstall: Installation, - config: AgentConfig, + agentPolicy: AgentPolicy, defaultOutput: Output ) { const packageInfo = await getPackageInfo({ @@ -216,14 +220,14 @@ async function addPackageToConfig( pkgVersion: packageToInstall.version, }); - const newPackageConfig = packageToPackageConfig( + const newPackagePolicy = packageToPackagePolicy( packageInfo, - config.id, + agentPolicy.id, defaultOutput.id, - config.namespace + agentPolicy.namespace ); - await packageConfigService.create(soClient, callCluster, newPackageConfig, { - bumpConfigRevision: false, + await packagePolicyService.create(soClient, callCluster, newPackagePolicy, { + bumpRevision: false, }); } diff --git a/x-pack/plugins/ingest_manager/server/types/index.tsx b/x-pack/plugins/ingest_manager/server/types/index.tsx index 5d0683a37dc5e4..8e3219a8c08e03 100644 --- a/x-pack/plugins/ingest_manager/server/types/index.tsx +++ b/x-pack/plugins/ingest_manager/server/types/index.tsx @@ -17,18 +17,18 @@ export { AgentEventSOAttributes, AgentAction, AgentActionSOAttributes, - PackageConfig, - PackageConfigInput, - PackageConfigInputStream, - NewPackageConfig, - UpdatePackageConfig, - PackageConfigSOAttributes, - FullAgentConfigInput, - FullAgentConfig, - AgentConfig, - AgentConfigSOAttributes, - NewAgentConfig, - AgentConfigStatus, + PackagePolicy, + PackagePolicyInput, + PackagePolicyInputStream, + NewPackagePolicy, + UpdatePackagePolicy, + PackagePolicySOAttributes, + FullAgentPolicyInput, + FullAgentPolicy, + AgentPolicy, + AgentPolicySOAttributes, + NewAgentPolicy, + AgentPolicyStatus, DataStream, Output, NewOutput, @@ -66,9 +66,9 @@ export { export type CallESAsCurrentUser = LegacyScopedClusterClient['callAsCurrentUser']; -export type AgentConfigUpdateHandler = ( +export type AgentPolicyUpdateHandler = ( action: 'created' | 'updated' | 'deleted', - agentConfigId: string + agentPolicyId: string ) => Promise; export * from './models'; diff --git a/x-pack/plugins/ingest_manager/server/types/models/agent.ts b/x-pack/plugins/ingest_manager/server/types/models/agent.ts index ea5eacc8e63d0b..5ad98cfd406226 100644 --- a/x-pack/plugins/ingest_manager/server/types/models/agent.ts +++ b/x-pack/plugins/ingest_manager/server/types/models/agent.ts @@ -43,7 +43,7 @@ const AgentEventBase = { payload: schema.maybe(schema.any()), agent_id: schema.string(), action_id: schema.maybe(schema.string()), - config_id: schema.maybe(schema.string()), + policy_id: schema.maybe(schema.string()), stream_id: schema.maybe(schema.string()), }; diff --git a/x-pack/plugins/ingest_manager/server/types/models/agent_config.ts b/x-pack/plugins/ingest_manager/server/types/models/agent_policy.ts similarity index 60% rename from x-pack/plugins/ingest_manager/server/types/models/agent_config.ts rename to x-pack/plugins/ingest_manager/server/types/models/agent_policy.ts index a9e14301cd7c3b..877d8e9e917141 100644 --- a/x-pack/plugins/ingest_manager/server/types/models/agent_config.ts +++ b/x-pack/plugins/ingest_manager/server/types/models/agent_policy.ts @@ -4,10 +4,10 @@ * you may not use this file except in compliance with the Elastic License. */ import { schema } from '@kbn/config-schema'; -import { PackageConfigSchema } from './package_config'; -import { AgentConfigStatus } from '../../../common'; +import { PackagePolicySchema } from './package_policy'; +import { AgentPolicyStatus } from '../../../common'; -const AgentConfigBaseSchema = { +const AgentPolicyBaseSchema = { name: schema.string({ minLength: 1 }), namespace: schema.string({ minLength: 1 }), description: schema.maybe(schema.string()), @@ -16,20 +16,20 @@ const AgentConfigBaseSchema = { ), }; -export const NewAgentConfigSchema = schema.object({ - ...AgentConfigBaseSchema, +export const NewAgentPolicySchema = schema.object({ + ...AgentPolicyBaseSchema, }); -export const AgentConfigSchema = schema.object({ - ...AgentConfigBaseSchema, +export const AgentPolicySchema = schema.object({ + ...AgentPolicyBaseSchema, id: schema.string(), status: schema.oneOf([ - schema.literal(AgentConfigStatus.Active), - schema.literal(AgentConfigStatus.Inactive), + schema.literal(AgentPolicyStatus.Active), + schema.literal(AgentPolicyStatus.Inactive), ]), - package_configs: schema.oneOf([ + package_policies: schema.oneOf([ schema.arrayOf(schema.string()), - schema.arrayOf(PackageConfigSchema), + schema.arrayOf(PackagePolicySchema), ]), updated_at: schema.string(), updated_by: schema.string(), diff --git a/x-pack/plugins/ingest_manager/server/types/models/enrollment_api_key.ts b/x-pack/plugins/ingest_manager/server/types/models/enrollment_api_key.ts index e563b39e53f507..919204f93ff21f 100644 --- a/x-pack/plugins/ingest_manager/server/types/models/enrollment_api_key.ts +++ b/x-pack/plugins/ingest_manager/server/types/models/enrollment_api_key.ts @@ -11,15 +11,5 @@ export const EnrollmentAPIKeySchema = schema.object({ api_key: schema.string(), name: schema.maybe(schema.string()), active: schema.boolean(), - config_id: schema.maybe(schema.string()), -}); - -export const EnrollmentAPIKeySOAttributesSchema = schema.object({ - api_key_id: schema.string(), - api_key: schema.string(), - name: schema.maybe(schema.string()), - active: schema.boolean(), - config_id: schema.maybe(schema.string()), - // ASK: Is this allowUnknown? How do we type this with config-schema? - // [k: string]: schema.any(), // allow to use it as saved object attributes type + policy_id: schema.maybe(schema.string()), }); diff --git a/x-pack/plugins/ingest_manager/server/types/models/index.ts b/x-pack/plugins/ingest_manager/server/types/models/index.ts index 268e87eb529be6..243a8a4e09e6e5 100644 --- a/x-pack/plugins/ingest_manager/server/types/models/index.ts +++ b/x-pack/plugins/ingest_manager/server/types/models/index.ts @@ -3,8 +3,8 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -export * from './agent_config'; +export * from './agent_policy'; export * from './agent'; -export * from './package_config'; +export * from './package_policy'; export * from './output'; export * from './enrollment_api_key'; diff --git a/x-pack/plugins/ingest_manager/server/types/models/package_config.ts b/x-pack/plugins/ingest_manager/server/types/models/package_policy.ts similarity index 85% rename from x-pack/plugins/ingest_manager/server/types/models/package_config.ts rename to x-pack/plugins/ingest_manager/server/types/models/package_policy.ts index 9b7ffb4f781750..81bfb599b4c9af 100644 --- a/x-pack/plugins/ingest_manager/server/types/models/package_config.ts +++ b/x-pack/plugins/ingest_manager/server/types/models/package_policy.ts @@ -13,11 +13,11 @@ const ConfigRecordSchema = schema.recordOf( }) ); -const PackageConfigBaseSchema = { +const PackagePolicyBaseSchema = { name: schema.string(), description: schema.maybe(schema.string()), namespace: schema.string({ minLength: 1 }), - config_id: schema.string(), + policy_id: schema.string(), enabled: schema.boolean(), package: schema.maybe( schema.object({ @@ -62,17 +62,17 @@ const PackageConfigBaseSchema = { ), }; -export const NewPackageConfigSchema = schema.object({ - ...PackageConfigBaseSchema, +export const NewPackagePolicySchema = schema.object({ + ...PackagePolicyBaseSchema, }); -export const UpdatePackageConfigSchema = schema.object({ - ...PackageConfigBaseSchema, +export const UpdatePackagePolicySchema = schema.object({ + ...PackagePolicyBaseSchema, version: schema.maybe(schema.string()), }); -export const PackageConfigSchema = schema.object({ - ...PackageConfigBaseSchema, +export const PackagePolicySchema = schema.object({ + ...PackagePolicyBaseSchema, id: schema.string(), version: schema.maybe(schema.string()), }); diff --git a/x-pack/plugins/ingest_manager/server/types/rest_spec/agent.ts b/x-pack/plugins/ingest_manager/server/types/rest_spec/agent.ts index 3e9209efcac047..3302b0ab84ba88 100644 --- a/x-pack/plugins/ingest_manager/server/types/rest_spec/agent.ts +++ b/x-pack/plugins/ingest_manager/server/types/rest_spec/agent.ts @@ -85,7 +85,7 @@ export const PutAgentReassignRequestSchema = { agentId: schema.string(), }), body: schema.object({ - config_id: schema.string(), + policy_id: schema.string(), }), }; @@ -117,6 +117,6 @@ export const UpdateAgentRequestSchema = { export const GetAgentStatusRequestSchema = { query: schema.object({ - configId: schema.maybe(schema.string()), + policyId: schema.maybe(schema.string()), }), }; diff --git a/x-pack/plugins/ingest_manager/server/types/rest_spec/agent_config.ts b/x-pack/plugins/ingest_manager/server/types/rest_spec/agent_policy.ts similarity index 58% rename from x-pack/plugins/ingest_manager/server/types/rest_spec/agent_config.ts rename to x-pack/plugins/ingest_manager/server/types/rest_spec/agent_policy.ts index 594bd141459c1d..bb02eb50a6ad4f 100644 --- a/x-pack/plugins/ingest_manager/server/types/rest_spec/agent_config.ts +++ b/x-pack/plugins/ingest_manager/server/types/rest_spec/agent_policy.ts @@ -4,50 +4,50 @@ * you may not use this file except in compliance with the Elastic License. */ import { schema } from '@kbn/config-schema'; -import { NewAgentConfigSchema } from '../models'; +import { NewAgentPolicySchema } from '../models'; import { ListWithKuerySchema } from './index'; -export const GetAgentConfigsRequestSchema = { +export const GetAgentPoliciesRequestSchema = { query: ListWithKuerySchema.extends({ full: schema.maybe(schema.boolean()), }), }; -export const GetOneAgentConfigRequestSchema = { +export const GetOneAgentPolicyRequestSchema = { params: schema.object({ - agentConfigId: schema.string(), + agentPolicyId: schema.string(), }), }; -export const CreateAgentConfigRequestSchema = { - body: NewAgentConfigSchema, +export const CreateAgentPolicyRequestSchema = { + body: NewAgentPolicySchema, query: schema.object({ sys_monitoring: schema.maybe(schema.boolean()), }), }; -export const UpdateAgentConfigRequestSchema = { - ...GetOneAgentConfigRequestSchema, - body: NewAgentConfigSchema, +export const UpdateAgentPolicyRequestSchema = { + ...GetOneAgentPolicyRequestSchema, + body: NewAgentPolicySchema, }; -export const CopyAgentConfigRequestSchema = { - ...GetOneAgentConfigRequestSchema, +export const CopyAgentPolicyRequestSchema = { + ...GetOneAgentPolicyRequestSchema, body: schema.object({ name: schema.string({ minLength: 1 }), description: schema.maybe(schema.string()), }), }; -export const DeleteAgentConfigRequestSchema = { +export const DeleteAgentPolicyRequestSchema = { body: schema.object({ - agentConfigId: schema.string(), + agentPolicyId: schema.string(), }), }; -export const GetFullAgentConfigRequestSchema = { +export const GetFullAgentPolicyRequestSchema = { params: schema.object({ - agentConfigId: schema.string(), + agentPolicyId: schema.string(), }), query: schema.object({ download: schema.maybe(schema.boolean()), diff --git a/x-pack/plugins/ingest_manager/server/types/rest_spec/enrollment_api_key.ts b/x-pack/plugins/ingest_manager/server/types/rest_spec/enrollment_api_key.ts index ff342bd1657702..397927ae792a49 100644 --- a/x-pack/plugins/ingest_manager/server/types/rest_spec/enrollment_api_key.ts +++ b/x-pack/plugins/ingest_manager/server/types/rest_spec/enrollment_api_key.ts @@ -29,7 +29,7 @@ export const DeleteEnrollmentAPIKeyRequestSchema = { export const PostEnrollmentAPIKeyRequestSchema = { body: schema.object({ name: schema.maybe(schema.string()), - config_id: schema.string(), + policy_id: schema.string(), expiration: schema.maybe(schema.string()), }), }; diff --git a/x-pack/plugins/ingest_manager/server/types/rest_spec/index.ts b/x-pack/plugins/ingest_manager/server/types/rest_spec/index.ts index f3ee868f43f00f..0f340b48634ea6 100644 --- a/x-pack/plugins/ingest_manager/server/types/rest_spec/index.ts +++ b/x-pack/plugins/ingest_manager/server/types/rest_spec/index.ts @@ -4,9 +4,9 @@ * you may not use this file except in compliance with the Elastic License. */ export * from './common'; -export * from './agent_config'; +export * from './agent_policy'; export * from './agent'; -export * from './package_config'; +export * from './package_policy'; export * from './epm'; export * from './enrollment_api_key'; export * from './install_script'; diff --git a/x-pack/plugins/ingest_manager/server/types/rest_spec/package_config.ts b/x-pack/plugins/ingest_manager/server/types/rest_spec/package_config.ts deleted file mode 100644 index 630fb55f2654d0..00000000000000 --- a/x-pack/plugins/ingest_manager/server/types/rest_spec/package_config.ts +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -import { schema } from '@kbn/config-schema'; -import { NewPackageConfigSchema, UpdatePackageConfigSchema } from '../models'; -import { ListWithKuerySchema } from './index'; - -export const GetPackageConfigsRequestSchema = { - query: ListWithKuerySchema, -}; - -export const GetOnePackageConfigRequestSchema = { - params: schema.object({ - packageConfigId: schema.string(), - }), -}; - -export const CreatePackageConfigRequestSchema = { - body: NewPackageConfigSchema, -}; - -export const UpdatePackageConfigRequestSchema = { - ...GetOnePackageConfigRequestSchema, - body: UpdatePackageConfigSchema, -}; - -export const DeletePackageConfigsRequestSchema = { - body: schema.object({ - packageConfigIds: schema.arrayOf(schema.string()), - }), -}; diff --git a/x-pack/plugins/ingest_manager/server/types/rest_spec/package_policy.ts b/x-pack/plugins/ingest_manager/server/types/rest_spec/package_policy.ts new file mode 100644 index 00000000000000..9e7d191ae35f3b --- /dev/null +++ b/x-pack/plugins/ingest_manager/server/types/rest_spec/package_policy.ts @@ -0,0 +1,33 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { schema } from '@kbn/config-schema'; +import { NewPackagePolicySchema, UpdatePackagePolicySchema } from '../models'; +import { ListWithKuerySchema } from './index'; + +export const GetPackagePoliciesRequestSchema = { + query: ListWithKuerySchema, +}; + +export const GetOnePackagePolicyRequestSchema = { + params: schema.object({ + packagePolicyId: schema.string(), + }), +}; + +export const CreatePackagePolicyRequestSchema = { + body: NewPackagePolicySchema, +}; + +export const UpdatePackagePolicyRequestSchema = { + ...GetOnePackagePolicyRequestSchema, + body: UpdatePackagePolicySchema, +}; + +export const DeletePackagePoliciesRequestSchema = { + body: schema.object({ + packagePolicyIds: schema.arrayOf(schema.string()), + }), +}; diff --git a/x-pack/plugins/security_solution/common/endpoint/generate_data.ts b/x-pack/plugins/security_solution/common/endpoint/generate_data.ts index 09f25fc074effe..0a6473b8338633 100644 --- a/x-pack/plugins/security_solution/common/endpoint/generate_data.ts +++ b/x-pack/plugins/security_solution/common/endpoint/generate_data.ts @@ -19,11 +19,11 @@ import { import { factory as policyFactory } from './models/policy_config'; import { parentEntityId } from './models/event'; import { - GetAgentConfigsResponseItem, + GetAgentPoliciesResponseItem, GetPackagesResponse, } from '../../../ingest_manager/common/types/rest_spec'; import { - AgentConfigStatus, + AgentPolicyStatus, EsAssetReference, InstallationStatus, KibanaAssetReference, @@ -1031,9 +1031,9 @@ export class EndpointDocGenerator { } /** - * Generates an Ingest `package config` that includes the Endpoint Policy data + * Generates an Ingest `package policy` that includes the Endpoint Policy data */ - public generatePolicyPackageConfig(): PolicyData { + public generatePolicyPackagePolicy(): PolicyData { const created = new Date(Date.now() - 8.64e7).toISOString(); // 24h ago return { id: this.seededUUIDv4(), @@ -1043,7 +1043,7 @@ export class EndpointDocGenerator { created_by: 'elastic', updated_at: new Date().toISOString(), updated_by: 'elastic', - config_id: this.seededUUIDv4(), + policy_id: this.seededUUIDv4(), enabled: true, output_id: '', inputs: [ @@ -1076,20 +1076,20 @@ export class EndpointDocGenerator { } /** - * Generate an Agent Configuration (ingest) + * Generate an Agent Policy (ingest) */ - public generateAgentConfig(): GetAgentConfigsResponseItem { + public generateAgentPolicy(): GetAgentPoliciesResponseItem { return { id: this.seededUUIDv4(), - name: 'Agent Config', - status: AgentConfigStatus.Active, + name: 'Agent Policy', + status: AgentPolicyStatus.Active, description: 'Some description', namespace: 'default', monitoring_enabled: ['logs', 'metrics'], revision: 2, updated_at: '2020-07-22T16:36:49.196Z', updated_by: 'elastic', - package_configs: ['852491f0-cc39-11ea-bac2-cdbf95b4b41a'], + package_policies: ['852491f0-cc39-11ea-bac2-cdbf95b4b41a'], agents: 0, }; } diff --git a/x-pack/plugins/security_solution/common/endpoint/types.ts b/x-pack/plugins/security_solution/common/endpoint/types.ts index 2a1c95caff3a3f..2b8de7ed16b08e 100644 --- a/x-pack/plugins/security_solution/common/endpoint/types.ts +++ b/x-pack/plugins/security_solution/common/endpoint/types.ts @@ -5,7 +5,7 @@ */ import { ApplicationStart } from 'kibana/public'; -import { NewPackageConfig, PackageConfig } from '../../../ingest_manager/common'; +import { NewPackagePolicy, PackagePolicy } from '../../../ingest_manager/common'; import { ManifestSchema } from './schema/manifest'; /** @@ -831,14 +831,14 @@ export enum ProtectionModes { } /** - * Endpoint Policy data, which extends Ingest's `PackageConfig` type + * Endpoint Policy data, which extends Ingest's `PackagePolicy` type */ -export type PolicyData = PackageConfig & NewPolicyData; +export type PolicyData = PackagePolicy & NewPolicyData; /** * New policy data. Used when updating the policy record via ingest APIs */ -export type NewPolicyData = NewPackageConfig & { +export type NewPolicyData = NewPackagePolicy & { inputs: [ { type: 'endpoint'; diff --git a/x-pack/plugins/security_solution/public/common/hooks/endpoint/use_navigate_to_app_event_handler.ts b/x-pack/plugins/security_solution/public/common/hooks/endpoint/use_navigate_to_app_event_handler.ts index cb4de29802e541..190009440529ca 100644 --- a/x-pack/plugins/security_solution/public/common/hooks/endpoint/use_navigate_to_app_event_handler.ts +++ b/x-pack/plugins/security_solution/public/common/hooks/endpoint/use_navigate_to_app_event_handler.ts @@ -25,8 +25,8 @@ type EventHandlerCallback = MouseEventHandlerSee configs + * const handleOnClick = useNavigateToAppEventHandler('ingestManager', {path: '#/policies'}) + * return See policies */ export const useNavigateToAppEventHandler = ( /** the app id - normally the value of the `id` in that plugin's `kibana.json` */ diff --git a/x-pack/plugins/security_solution/public/common/mock/endpoint/dependencies_start_mock.ts b/x-pack/plugins/security_solution/public/common/mock/endpoint/dependencies_start_mock.ts index 9cf99f2442aabc..5f8ab723df107a 100644 --- a/x-pack/plugins/security_solution/public/common/mock/endpoint/dependencies_start_mock.ts +++ b/x-pack/plugins/security_solution/public/common/mock/endpoint/dependencies_start_mock.ts @@ -6,7 +6,7 @@ import { IngestManagerStart, - registerPackageConfigComponent, + registerPackagePolicyComponent, } from '../../../../../ingest_manager/public'; import { dataPluginMock, @@ -61,7 +61,7 @@ export const depsStartMock: () => DepsStartMock = () => { data: dataMock, ingestManager: { isInitialized: () => Promise.resolve(true), - registerPackageConfigComponent, + registerPackagePolicyComponent, }, }; }; diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/middleware.ts b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/middleware.ts index fa2dbe084c1a42..f56f28bfef39ac 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/middleware.ts +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/middleware.ts @@ -18,11 +18,11 @@ import { } from './selectors'; import { EndpointState } from '../types'; import { - sendGetEndpointSpecificPackageConfigs, + sendGetEndpointSpecificPackagePolicies, sendGetEndpointSecurityPackage, - sendGetAgentConfigList, + sendGetAgentPolicyList, } from '../../policy/store/policy_list/services/ingest'; -import { AGENT_CONFIG_SAVED_OBJECT_TYPE } from '../../../../../../ingest_manager/common'; +import { AGENT_POLICY_SAVED_OBJECT_TYPE } from '../../../../../../ingest_manager/common'; export const endpointMiddlewareFactory: ImmutableMiddlewareFactory = (coreStart) => { return ({ getState, dispatch }) => (next) => async (action) => { @@ -105,7 +105,7 @@ export const endpointMiddlewareFactory: ImmutableMiddlewareFactory((list, agentConfig) => { - (agentConfig.package_configs as string[]).forEach((packageConfig) => { - list[packageConfig as string] = true; + ).items.reduce((list, agentPolicy) => { + (agentPolicy.package_policies as string[]).forEach((packagePolicy) => { + list[packagePolicy as string] = true; }); return list; }, {}); diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/mock_endpoint_result_list.ts b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/mock_endpoint_result_list.ts index 2f0b66624f379e..aa9bef7bb5417e 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/mock_endpoint_result_list.ts +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/store/mock_endpoint_result_list.ts @@ -14,12 +14,12 @@ import { } from '../../../../../common/endpoint/types'; import { EndpointDocGenerator } from '../../../../../common/endpoint/generate_data'; import { - INGEST_API_AGENT_CONFIGS, + INGEST_API_AGENT_POLICIES, INGEST_API_EPM_PACKAGES, - INGEST_API_PACKAGE_CONFIGS, + INGEST_API_PACKAGE_POLICIES, } from '../../policy/store/policy_list/services/ingest'; import { - GetAgentConfigsResponse, + GetAgentPoliciesResponse, GetPackagesResponse, } from '../../../../../../ingest_manager/common/types/rest_spec'; import { GetPolicyListResponse } from '../../policy/types'; @@ -76,13 +76,13 @@ export const mockEndpointDetailsApiResult = (): HostInfo => { const endpointListApiPathHandlerMocks = ({ endpointsResults = mockEndpointResultList({ total: 3 }).hosts, epmPackages = [generator.generateEpmPackage()], - endpointPackageConfigs = [], + endpointPackagePolicies = [], policyResponse = generator.generatePolicyResponse(), }: { /** route handlers will be setup for each individual host in this array */ endpointsResults?: HostResultList['hosts']; epmPackages?: GetPackagesResponse['response']; - endpointPackageConfigs?: GetPolicyListResponse['items']; + endpointPackagePolicies?: GetPolicyListResponse['items']; policyResponse?: HostPolicyResponse; } = {}) => { const apiHandlers = { @@ -105,14 +105,14 @@ const endpointListApiPathHandlerMocks = ({ }, // Do policies referenced in endpoint list exist - // just returns 1 single agent config that includes all of the packageConfig IDs provided - [INGEST_API_AGENT_CONFIGS]: (): GetAgentConfigsResponse => { - const agentConfig = generator.generateAgentConfig(); - (agentConfig.package_configs as string[]).push( - ...endpointPackageConfigs.map((packageConfig) => packageConfig.id) + // just returns 1 single agent policy that includes all of the packagePolicy IDs provided + [INGEST_API_AGENT_POLICIES]: (): GetAgentPoliciesResponse => { + const agentPolicy = generator.generateAgentPolicy(); + (agentPolicy.package_policies as string[]).push( + ...endpointPackagePolicies.map((packagePolicy) => packagePolicy.id) ); return { - items: [agentConfig], + items: [agentPolicy], total: 10, success: true, perPage: 10, @@ -125,13 +125,13 @@ const endpointListApiPathHandlerMocks = ({ return { policy_response: policyResponse }; }, - // List of Policies (package configs) for onboarding - [INGEST_API_PACKAGE_CONFIGS]: (): GetPolicyListResponse => { + // List of Policies (package policies) for onboarding + [INGEST_API_PACKAGE_POLICIES]: (): GetPolicyListResponse => { return { - items: endpointPackageConfigs, + items: endpointPackagePolicies, page: 1, perPage: 10, - total: endpointPackageConfigs?.length, + total: endpointPackagePolicies?.length, success: true, }; }, diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/endpoint_details.tsx b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/endpoint_details.tsx index bd499ee6abb245..b76b7e51b2c1b0 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/endpoint_details.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/endpoint_details.tsx @@ -29,7 +29,7 @@ import { LinkToApp } from '../../../../../common/components/endpoint/link_to_app import { getEndpointDetailsPath } from '../../../../common/routing'; import { SecurityPageName } from '../../../../../app/types'; import { useFormatUrl } from '../../../../../common/components/link_to'; -import { AgentDetailsReassignConfigAction } from '../../../../../../../ingest_manager/public'; +import { AgentDetailsReassignPolicyAction } from '../../../../../../../ingest_manager/public'; import { EndpointPolicyLink } from '../components/endpoint_policy_link'; const HostIds = styled(EuiListGroupItem)` @@ -103,7 +103,7 @@ export const EndpointDetails = memo(({ details }: { details: HostMetadata }) => const agentDetailsWithFlyoutPath = `${agentDetailsAppPath}${openReassignFlyoutSearch}`; const agentDetailsWithFlyoutUrl = `${agentDetailsUrl}${openReassignFlyoutSearch}`; const handleReassignEndpointsClick = useNavigateToAppEventHandler< - AgentDetailsReassignConfigAction + AgentDetailsReassignPolicyAction >(ingestAppId, { path: agentDetailsWithFlyoutPath, state: { diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.test.tsx b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.test.tsx index fe06bcc8131f80..a504390344e37f 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.test.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.test.tsx @@ -73,7 +73,7 @@ describe('when on the list page', () => { beforeEach(async () => { setEndpointListApiMockImplementation(coreStart.http, { endpointsResults: [], - endpointPackageConfigs: mockPolicyResultList({ total: 3 }).items, + endpointPackagePolicies: mockPolicyResultList({ total: 3 }).items, }); }); afterEach(() => { @@ -140,12 +140,12 @@ describe('when on the list page', () => { }); // Make sure that the first policy id in the host result is not set as non-existent - const ingestPackageConfigs = mockPolicyResultList({ total: 1 }).items; - ingestPackageConfigs[0].id = firstPolicyID; + const ingestPackagePolicies = mockPolicyResultList({ total: 1 }).items; + ingestPackagePolicies[0].id = firstPolicyID; setEndpointListApiMockImplementation(coreStart.http, { endpointsResults: hostListData, - endpointPackageConfigs: ingestPackageConfigs, + endpointPackagePolicies: ingestPackagePolicies, }); }); }); @@ -332,12 +332,12 @@ describe('when on the list page', () => { agentId = hostDetails.metadata.elastic.agent.id; - const policy = docGenerator.generatePolicyPackageConfig(); + const policy = docGenerator.generatePolicyPackagePolicy(); policy.id = hostDetails.metadata.Endpoint.policy.applied.id; setEndpointListApiMockImplementation(coreStart.http, { endpointsResults: [hostDetails], - endpointPackageConfigs: [policy], + endpointPackagePolicies: [policy], }); reactTestingLibrary.act(() => { diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.tsx b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.tsx index 611e69391ab069..8b8ac3a1d3587d 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.tsx @@ -35,8 +35,8 @@ import { PolicyEmptyState, HostsEmptyState } from '../../../components/managemen import { FormattedDate } from '../../../../common/components/formatted_date'; import { useNavigateToAppEventHandler } from '../../../../common/hooks/endpoint/use_navigate_to_app_event_handler'; import { - CreatePackageConfigRouteState, - AgentConfigDetailsDeployAgentAction, + CreatePackagePolicyRouteState, + AgentPolicyDetailsDeployAgentAction, } from '../../../../../../ingest_manager/public'; import { SecurityPageName } from '../../../../app/types'; import { getEndpointListPath, getEndpointDetailsPath } from '../../../common/routing'; @@ -115,7 +115,7 @@ export const EndpointList = () => { [history, queryParams] ); - const handleCreatePolicyClick = useNavigateToAppEventHandler( + const handleCreatePolicyClick = useNavigateToAppEventHandler( 'ingestManager', { path: `#/integrations${ @@ -136,9 +136,9 @@ export const EndpointList = () => { ); const handleDeployEndpointsClick = useNavigateToAppEventHandler< - AgentConfigDetailsDeployAgentAction + AgentPolicyDetailsDeployAgentAction >('ingestManager', { - path: `#/configs/${selectedPolicyId}?openEnrollmentFlyout=true`, + path: `#/policies/${selectedPolicyId}?openEnrollmentFlyout=true`, state: { onDoneNavigateTo: [ 'securitySolution:administration', @@ -150,9 +150,9 @@ export const EndpointList = () => { const selectionOptions = useMemo(() => { return policyItems.map((item) => { return { - key: item.config_id, + key: item.policy_id, label: item.name, - checked: selectedPolicyId === item.config_id ? 'on' : undefined, + checked: selectedPolicyId === item.policy_id ? 'on' : undefined, }; }); }, [policyItems, selectedPolicyId]); diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_details/index.test.ts b/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_details/index.test.ts index d3ec0670d29c54..0eedecef22170c 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_details/index.test.ts +++ b/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_details/index.test.ts @@ -36,7 +36,7 @@ describe('policy details: ', () => { created_by: '', updated_at: '', updated_by: '', - config_id: '', + policy_id: '', enabled: true, output_id: '', inputs: [ @@ -213,7 +213,7 @@ describe('policy details: ', () => { expect(JSON.parse(lastPutCallPayload.body as string)).toEqual({ name: '', description: '', - config_id: '', + policy_id: '', enabled: true, output_id: '', inputs: [ diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_details/middleware.ts b/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_details/middleware.ts index 1d9e3c2198b289..250a5b25230f1d 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_details/middleware.ts +++ b/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_details/middleware.ts @@ -14,9 +14,9 @@ import { getPolicyDataForUpdate, } from './selectors'; import { - sendGetPackageConfig, - sendGetFleetAgentStatusForConfig, - sendPutPackageConfig, + sendGetPackagePolicy, + sendGetFleetAgentStatusForPolicy, + sendPutPackagePolicy, } from '../policy_list/services/ingest'; import { NewPolicyData, PolicyData } from '../../../../../../common/endpoint/types'; import { ImmutableMiddlewareFactory } from '../../../../../common/store'; @@ -35,7 +35,7 @@ export const policyDetailsMiddlewareFactory: ImmutableMiddlewareFactory { if (!error.response || error.response.status !== 409) { return Promise.reject(error); } // Handle 409 error (version conflict) here, by using the latest document - // for the package config and adding the updated policy to it, ensuring that + // for the package policy and adding the updated policy to it, ensuring that // any recent updates to `manifest_artifacts` are retained. - return sendGetPackageConfig(http, id).then((packageConfig) => { - const latestUpdatedPolicyItem = packageConfig.item; + return sendGetPackagePolicy(http, id).then((packagePolicy) => { + const latestUpdatedPolicyItem = packagePolicy.item; latestUpdatedPolicyItem.inputs[0].config.policy = updatedPolicyItem.inputs[0].config.policy; - return sendPutPackageConfig( + return sendPutPackagePolicy( http, id, getPolicyDataForUpdate(latestUpdatedPolicyItem) as NewPolicyData diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_details/selectors.ts b/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_details/selectors.ts index d780828fc88339..c236b2841fc858 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_details/selectors.ts +++ b/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_details/selectors.ts @@ -22,7 +22,7 @@ import { ManagementRoutePolicyDetailsParams } from '../../../../types'; export const policyDetails = (state: Immutable) => state.policyItem; /** - * Given a Policy Data (package config) object, return back a new object with only the field + * Given a Policy Data (package policy) object, return back a new object with only the field * needed for an Update/Create API action * @param policy */ diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_list/action.ts b/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_list/action.ts index b04b2f085689e7..562cd6807f68a9 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_list/action.ts +++ b/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_list/action.ts @@ -33,7 +33,7 @@ interface UserClickedPolicyListDeleteButton { interface UserOpenedPolicyListDeleteModal { type: 'userOpenedPolicyListDeleteModal'; - payload: { agentConfigId: string }; + payload: { agentPolicyId: string }; } interface ServerDeletedPolicyFailure { diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_list/index.test.ts b/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_list/index.test.ts index 6ee6a4232f7cfb..03e65bd6f43cbe 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_list/index.test.ts +++ b/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_list/index.test.ts @@ -8,7 +8,7 @@ import { PolicyListState } from '../../types'; import { Store, applyMiddleware, createStore } from 'redux'; import { coreMock } from '../../../../../../../../../src/core/public/mocks'; -import { PACKAGE_CONFIG_SAVED_OBJECT_TYPE } from '../../../../../../../ingest_manager/common'; +import { PACKAGE_POLICY_SAVED_OBJECT_TYPE } from '../../../../../../../ingest_manager/common'; import { policyListReducer } from './reducer'; import { policyListMiddlewareFactory } from './middleware'; @@ -22,7 +22,7 @@ import { } from './selectors'; import { DepsStartMock, depsStartMock } from '../../../../../common/mock/endpoint'; import { setPolicyListApiMockImplementation } from './test_mock_utils'; -import { INGEST_API_PACKAGE_CONFIGS } from './services/ingest'; +import { INGEST_API_PACKAGE_POLICIES } from './services/ingest'; import { createSpyMiddleware, MiddlewareActionSpyHelper, @@ -167,9 +167,9 @@ describe('policy list store concerns', () => { }, }); await waitForAction('serverReturnedPolicyListData'); - expect(fakeCoreStart.http.get).toHaveBeenCalledWith(INGEST_API_PACKAGE_CONFIGS, { + expect(fakeCoreStart.http.get).toHaveBeenCalledWith(INGEST_API_PACKAGE_POLICIES, { query: { - kuery: `${PACKAGE_CONFIG_SAVED_OBJECT_TYPE}.package.name: endpoint`, + kuery: `${PACKAGE_POLICY_SAVED_OBJECT_TYPE}.package.name: endpoint`, page: 1, perPage: 10, }, @@ -190,9 +190,9 @@ describe('policy list store concerns', () => { it('uses pagination params from url', async () => { dispatchUserChangedUrl('?page_size=50&page_index=0'); await waitForAction('serverReturnedPolicyListData'); - expect(fakeCoreStart.http.get).toHaveBeenCalledWith(INGEST_API_PACKAGE_CONFIGS, { + expect(fakeCoreStart.http.get).toHaveBeenCalledWith(INGEST_API_PACKAGE_POLICIES, { query: { - kuery: `${PACKAGE_CONFIG_SAVED_OBJECT_TYPE}.package.name: endpoint`, + kuery: `${PACKAGE_POLICY_SAVED_OBJECT_TYPE}.package.name: endpoint`, page: 1, perPage: 50, }, @@ -213,9 +213,9 @@ describe('policy list store concerns', () => { it('accepts only positive numbers for page_index and page_size', async () => { dispatchUserChangedUrl('?page_size=-50&page_index=-99'); await waitForAction('serverReturnedPolicyListData'); - expect(fakeCoreStart.http.get).toHaveBeenCalledWith(INGEST_API_PACKAGE_CONFIGS, { + expect(fakeCoreStart.http.get).toHaveBeenCalledWith(INGEST_API_PACKAGE_POLICIES, { query: { - kuery: `${PACKAGE_CONFIG_SAVED_OBJECT_TYPE}.package.name: endpoint`, + kuery: `${PACKAGE_POLICY_SAVED_OBJECT_TYPE}.package.name: endpoint`, page: 1, perPage: 10, }, @@ -224,9 +224,9 @@ describe('policy list store concerns', () => { it('it ignores non-numeric values for page_index and page_size', async () => { dispatchUserChangedUrl('?page_size=fifty&page_index=ten'); await waitForAction('serverReturnedPolicyListData'); - expect(fakeCoreStart.http.get).toHaveBeenCalledWith(INGEST_API_PACKAGE_CONFIGS, { + expect(fakeCoreStart.http.get).toHaveBeenCalledWith(INGEST_API_PACKAGE_POLICIES, { query: { - kuery: `${PACKAGE_CONFIG_SAVED_OBJECT_TYPE}.package.name: endpoint`, + kuery: `${PACKAGE_POLICY_SAVED_OBJECT_TYPE}.package.name: endpoint`, page: 1, perPage: 10, }, @@ -235,9 +235,9 @@ describe('policy list store concerns', () => { it('accepts only known values for `page_size`', async () => { dispatchUserChangedUrl('?page_size=300&page_index=10'); await waitForAction('serverReturnedPolicyListData'); - expect(fakeCoreStart.http.get).toHaveBeenCalledWith(INGEST_API_PACKAGE_CONFIGS, { + expect(fakeCoreStart.http.get).toHaveBeenCalledWith(INGEST_API_PACKAGE_POLICIES, { query: { - kuery: `${PACKAGE_CONFIG_SAVED_OBJECT_TYPE}.package.name: endpoint`, + kuery: `${PACKAGE_POLICY_SAVED_OBJECT_TYPE}.package.name: endpoint`, page: 11, perPage: 10, }, @@ -264,9 +264,9 @@ describe('policy list store concerns', () => { expect(endpointPackageVersion(store.getState())).toEqual('0.5.0'); fakeCoreStart.http.get.mockClear(); dispatchUserChangedUrl('?page_size=10&page_index=11'); - expect(fakeCoreStart.http.get).toHaveBeenCalledWith(INGEST_API_PACKAGE_CONFIGS, { + expect(fakeCoreStart.http.get).toHaveBeenCalledWith(INGEST_API_PACKAGE_POLICIES, { query: { - kuery: `${PACKAGE_CONFIG_SAVED_OBJECT_TYPE}.package.name: endpoint`, + kuery: `${PACKAGE_POLICY_SAVED_OBJECT_TYPE}.package.name: endpoint`, page: 12, perPage: 10, }, diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_list/middleware.ts b/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_list/middleware.ts index 6fe555113617d9..fddd242e092ade 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_list/middleware.ts +++ b/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_list/middleware.ts @@ -6,17 +6,17 @@ import { GetPolicyListResponse, PolicyListState } from '../../types'; import { - sendGetEndpointSpecificPackageConfigs, - sendDeletePackageConfig, - sendGetFleetAgentStatusForConfig, + sendGetEndpointSpecificPackagePolicies, + sendDeletePackagePolicy, + sendGetFleetAgentStatusForPolicy, sendGetEndpointSecurityPackage, } from './services/ingest'; import { endpointPackageInfo, isOnPolicyListPage, urlSearchParams } from './selectors'; import { ImmutableMiddlewareFactory } from '../../../../../common/store'; import { initialPolicyListState } from './reducer'; import { - DeletePackageConfigsResponse, - DeletePackageConfigsRequest, + DeletePackagePoliciesResponse, + DeletePackagePoliciesRequest, GetAgentStatusResponse, } from '../../../../../../../ingest_manager/common'; @@ -57,7 +57,7 @@ export const policyListMiddlewareFactory: ImmutableMiddlewareFactory { @@ -21,22 +21,22 @@ describe('ingest service', () => { http = httpServiceMock.createStartContract(); }); - describe('sendGetEndpointSpecificPackageConfigs()', () => { + describe('sendGetEndpointSpecificPackagePolicies()', () => { it('auto adds kuery to api request', async () => { - await sendGetEndpointSpecificPackageConfigs(http); - expect(http.get).toHaveBeenCalledWith('/api/ingest_manager/package_configs', { + await sendGetEndpointSpecificPackagePolicies(http); + expect(http.get).toHaveBeenCalledWith('/api/ingest_manager/package_policies', { query: { - kuery: `${PACKAGE_CONFIG_SAVED_OBJECT_TYPE}.package.name: endpoint`, + kuery: `${PACKAGE_POLICY_SAVED_OBJECT_TYPE}.package.name: endpoint`, }, }); }); it('supports additional KQL to be defined on input for query params', async () => { - await sendGetEndpointSpecificPackageConfigs(http, { + await sendGetEndpointSpecificPackagePolicies(http, { query: { kuery: 'someValueHere', page: 1, perPage: 10 }, }); - expect(http.get).toHaveBeenCalledWith('/api/ingest_manager/package_configs', { + expect(http.get).toHaveBeenCalledWith('/api/ingest_manager/package_policies', { query: { - kuery: `someValueHere and ${PACKAGE_CONFIG_SAVED_OBJECT_TYPE}.package.name: endpoint`, + kuery: `someValueHere and ${PACKAGE_POLICY_SAVED_OBJECT_TYPE}.package.name: endpoint`, perPage: 10, page: 1, }, @@ -44,14 +44,14 @@ describe('ingest service', () => { }); }); - describe('sendGetPackageConfig()', () => { + describe('sendGetPackagePolicy()', () => { it('builds correct API path', async () => { - await sendGetPackageConfig(http, '123'); - expect(http.get).toHaveBeenCalledWith('/api/ingest_manager/package_configs/123', undefined); + await sendGetPackagePolicy(http, '123'); + expect(http.get).toHaveBeenCalledWith('/api/ingest_manager/package_policies/123', undefined); }); it('supports http options', async () => { - await sendGetPackageConfig(http, '123', { query: { page: 1 } }); - expect(http.get).toHaveBeenCalledWith('/api/ingest_manager/package_configs/123', { + await sendGetPackagePolicy(http, '123', { query: { page: 1 } }); + expect(http.get).toHaveBeenCalledWith('/api/ingest_manager/package_policies/123', { query: { page: 1, }, diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_list/services/ingest.ts b/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_list/services/ingest.ts index 266faf9eae32c9..e3b12e06a7025f 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_list/services/ingest.ts +++ b/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_list/services/ingest.ts @@ -6,127 +6,127 @@ import { HttpFetchOptions, HttpStart } from 'kibana/public'; import { - GetPackageConfigsRequest, + GetPackagePoliciesRequest, GetAgentStatusResponse, - DeletePackageConfigsResponse, - DeletePackageConfigsRequest, - PACKAGE_CONFIG_SAVED_OBJECT_TYPE, + DeletePackagePoliciesResponse, + DeletePackagePoliciesRequest, + PACKAGE_POLICY_SAVED_OBJECT_TYPE, GetPackagesResponse, - GetAgentConfigsRequest, - GetAgentConfigsResponse, + GetAgentPoliciesRequest, + GetAgentPoliciesResponse, } from '../../../../../../../../ingest_manager/common'; import { GetPolicyListResponse, GetPolicyResponse, UpdatePolicyResponse } from '../../../types'; import { NewPolicyData } from '../../../../../../../common/endpoint/types'; const INGEST_API_ROOT = `/api/ingest_manager`; -export const INGEST_API_PACKAGE_CONFIGS = `${INGEST_API_ROOT}/package_configs`; -export const INGEST_API_AGENT_CONFIGS = `${INGEST_API_ROOT}/agent_configs`; +export const INGEST_API_PACKAGE_POLICIES = `${INGEST_API_ROOT}/package_policies`; +export const INGEST_API_AGENT_POLICIES = `${INGEST_API_ROOT}/agent_policies`; const INGEST_API_FLEET = `${INGEST_API_ROOT}/fleet`; const INGEST_API_FLEET_AGENT_STATUS = `${INGEST_API_FLEET}/agent-status`; export const INGEST_API_EPM_PACKAGES = `${INGEST_API_ROOT}/epm/packages`; -const INGEST_API_DELETE_PACKAGE_CONFIG = `${INGEST_API_PACKAGE_CONFIGS}/delete`; +const INGEST_API_DELETE_PACKAGE_POLICY = `${INGEST_API_PACKAGE_POLICIES}/delete`; /** - * Retrieves a list of endpoint specific package configs (those created with a `package.name` of + * Retrieves a list of endpoint specific package policies (those created with a `package.name` of * `endpoint`) from Ingest * @param http * @param options */ -export const sendGetEndpointSpecificPackageConfigs = ( +export const sendGetEndpointSpecificPackagePolicies = ( http: HttpStart, - options: HttpFetchOptions & Partial = {} + options: HttpFetchOptions & Partial = {} ): Promise => { - return http.get(INGEST_API_PACKAGE_CONFIGS, { + return http.get(INGEST_API_PACKAGE_POLICIES, { ...options, query: { ...options.query, kuery: `${ options?.query?.kuery ? `${options.query.kuery} and ` : '' - }${PACKAGE_CONFIG_SAVED_OBJECT_TYPE}.package.name: endpoint`, + }${PACKAGE_POLICY_SAVED_OBJECT_TYPE}.package.name: endpoint`, }, }); }; /** - * Retrieves a single package config based on ID from ingest + * Retrieves a single package policy based on ID from ingest * @param http - * @param packageConfigId + * @param packagePolicyId * @param options */ -export const sendGetPackageConfig = ( +export const sendGetPackagePolicy = ( http: HttpStart, - packageConfigId: string, + packagePolicyId: string, options?: HttpFetchOptions ) => { - return http.get(`${INGEST_API_PACKAGE_CONFIGS}/${packageConfigId}`, options); + return http.get(`${INGEST_API_PACKAGE_POLICIES}/${packagePolicyId}`, options); }; /** - * Retrieves a single package config based on ID from ingest + * Retrieves a single package policy based on ID from ingest * @param http * @param body * @param options */ -export const sendDeletePackageConfig = ( +export const sendDeletePackagePolicy = ( http: HttpStart, - body: DeletePackageConfigsRequest, + body: DeletePackagePoliciesRequest, options?: HttpFetchOptions ) => { - return http.post(INGEST_API_DELETE_PACKAGE_CONFIG, { + return http.post(INGEST_API_DELETE_PACKAGE_POLICY, { ...options, body: JSON.stringify(body.body), }); }; /** - * Retrieve a list of Agent Configurations + * Retrieve a list of Agent Policies * @param http * @param options */ -export const sendGetAgentConfigList = ( +export const sendGetAgentPolicyList = ( http: HttpStart, - options: HttpFetchOptions & GetAgentConfigsRequest + options: HttpFetchOptions & GetAgentPoliciesRequest ) => { - return http.get(INGEST_API_AGENT_CONFIGS, options); + return http.get(INGEST_API_AGENT_POLICIES, options); }; /** - * Updates a package config + * Updates a package policy * * @param http - * @param packageConfigId - * @param packageConfig + * @param packagePolicyId + * @param packagePolicy * @param options */ -export const sendPutPackageConfig = ( +export const sendPutPackagePolicy = ( http: HttpStart, - packageConfigId: string, - packageConfig: NewPolicyData, + packagePolicyId: string, + packagePolicy: NewPolicyData, options: Exclude = {} ): Promise => { - return http.put(`${INGEST_API_PACKAGE_CONFIGS}/${packageConfigId}`, { + return http.put(`${INGEST_API_PACKAGE_POLICIES}/${packagePolicyId}`, { ...options, - body: JSON.stringify(packageConfig), + body: JSON.stringify(packagePolicy), }); }; /** - * Get a status summary for all Agents that are currently assigned to a given agent configuration + * Get a status summary for all Agents that are currently assigned to a given agent policy * * @param http - * @param configId + * @param policyId * @param options */ -export const sendGetFleetAgentStatusForConfig = ( +export const sendGetFleetAgentStatusForPolicy = ( http: HttpStart, - /** the Agent (fleet) configuration id */ - configId: string, + /** the Agent (fleet) policy id */ + policyId: string, options: Exclude = {} ): Promise => { return http.get(INGEST_API_FLEET_AGENT_STATUS, { ...options, query: { - configId, + policyId, }, }); }; diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_list/test_mock_utils.ts b/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_list/test_mock_utils.ts index 3c9d5fde9b826b..5ef01c00dbf166 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_list/test_mock_utils.ts +++ b/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_list/test_mock_utils.ts @@ -5,7 +5,7 @@ */ import { HttpStart } from 'kibana/public'; -import { INGEST_API_EPM_PACKAGES, INGEST_API_PACKAGE_CONFIGS } from './services/ingest'; +import { INGEST_API_EPM_PACKAGES, INGEST_API_PACKAGE_POLICIES } from './services/ingest'; import { EndpointDocGenerator } from '../../../../../../common/endpoint/generate_data'; import { GetPolicyListResponse } from '../../types'; import { GetPackagesResponse } from '../../../../../../../ingest_manager/common'; @@ -57,7 +57,7 @@ export const mockPolicyResultList: (options?: { const policies = []; for (let index = 0; index < actualCountToReturn; index++) { - policies.push(generator.generatePolicyPackageConfig()); + policies.push(generator.generatePolicyPackagePolicy()); } const mock: GetPolicyListResponse = { items: policies, @@ -75,7 +75,7 @@ export const mockPolicyResultList: (options?: { */ export const policyListApiPathHandlers = (totalPolicies: number = 1) => { return { - [INGEST_API_PACKAGE_CONFIGS]: () => { + [INGEST_API_PACKAGE_POLICIES]: () => { return mockPolicyResultList({ total: totalPolicies }); }, [INGEST_API_EPM_PACKAGES]: (): GetPackagesResponse => { diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/types.ts b/x-pack/plugins/security_solution/public/management/pages/policy/types.ts index 4a870016326be8..c7d426da055084 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/types.ts +++ b/x-pack/plugins/security_solution/public/management/pages/policy/types.ts @@ -14,10 +14,10 @@ import { import { ServerApiError } from '../../../common/types'; import { GetAgentStatusResponse, - GetOnePackageConfigResponse, - GetPackageConfigsResponse, + GetOnePackagePolicyResponse, + GetPackagePoliciesResponse, GetPackagesResponse, - UpdatePackageConfigResponse, + UpdatePackagePolicyResponse, } from '../../../../../ingest_manager/common'; /** @@ -44,7 +44,7 @@ export interface PolicyListState { isDeleting: boolean; /** Deletion status */ deleteStatus?: boolean; - /** A summary of stats for the agents associated with a given Fleet Agent Configuration */ + /** A summary of stats for the agents associated with a given Fleet Agent Policy */ agentStatusSummary?: GetAgentStatusResponse['results']; } @@ -59,7 +59,7 @@ export interface PolicyDetailsState { isLoading: boolean; /** current location of the application */ location?: Immutable; - /** A summary of stats for the agents associated with a given Fleet Agent Configuration */ + /** A summary of stats for the agents associated with a given Fleet Agent Policy */ agentStatusSummary?: GetAgentStatusResponse['results']; /** Status of an update to the policy */ updateStatus?: { @@ -169,14 +169,14 @@ export type KeysByValueCriteria = { /** Returns an array of the policy OSes that have a malware protection field */ export type MalwareProtectionOSes = KeysByValueCriteria; -export interface GetPolicyListResponse extends GetPackageConfigsResponse { +export interface GetPolicyListResponse extends GetPackagePoliciesResponse { items: PolicyData[]; } -export interface GetPolicyResponse extends GetOnePackageConfigResponse { +export interface GetPolicyResponse extends GetOnePackagePolicyResponse { item: PolicyData; } -export interface UpdatePolicyResponse extends UpdatePackageConfigResponse { +export interface UpdatePolicyResponse extends UpdatePackagePolicyResponse { item: PolicyData; } diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/configure_package_config.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/configure_package_policy.tsx similarity index 73% rename from x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/configure_package_config.tsx rename to x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/configure_package_policy.tsx index 2b08bfd2b282b1..b03069a739e352 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/configure_package_config.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/configure_package_policy.tsx @@ -9,27 +9,27 @@ import { FormattedMessage } from '@kbn/i18n/react'; import { EuiCallOut, EuiText, EuiSpacer } from '@elastic/eui'; import { LinkToApp } from '../../../../../common/components/endpoint/link_to_app'; import { - CustomConfigurePackageConfigContent, - CustomConfigurePackageConfigProps, + CustomConfigurePackagePolicyContent, + CustomConfigurePackagePolicyProps, } from '../../../../../../../ingest_manager/public'; import { getPolicyDetailPath } from '../../../../common/routing'; import { MANAGEMENT_APP_ID } from '../../../../common/constants'; import { PolicyDetailsRouteState } from '../../../../../../common/endpoint/types'; /** - * Exports Endpoint-specific package config instructions - * for use in the Ingest app create / edit package config + * Exports Endpoint-specific package policy instructions + * for use in the Ingest app create / edit package policy */ -export const ConfigureEndpointPackageConfig = memo( +export const ConfigureEndpointPackagePolicy = memo( ({ from, - packageConfigId, - packageConfig: { config_id: agentConfigId }, - }: CustomConfigurePackageConfigProps) => { + packagePolicyId, + packagePolicy: { policy_id: agentPolicyId }, + }: CustomConfigurePackagePolicyProps) => { let policyUrl = ''; - if (from === 'edit' && packageConfigId) { + if (from === 'edit' && packagePolicyId) { // Cannot use formalUrl here since the code is called in Ingest, which does not use redux - policyUrl = getPolicyDetailPath(packageConfigId); + policyUrl = getPolicyDetailPath(packagePolicyId); } const policyDetailRouteState = useMemo((): undefined | PolicyDetailsRouteState => { @@ -39,26 +39,26 @@ export const ConfigureEndpointPackageConfig = memo

{from === 'edit' ? ( @@ -78,8 +78,8 @@ export const ConfigureEndpointPackageConfig = memo ) : ( )}

@@ -90,4 +90,4 @@ export const ConfigureEndpointPackageConfig = memo { let middlewareSpy: AppContextTestRender['middlewareSpy']; let http: typeof coreStart.http; let render: (ui: Parameters[0]) => ReturnType; - let policyPackageConfig: ReturnType; + let policyPackagePolicy: ReturnType; let policyView: ReturnType; beforeEach(() => { @@ -78,8 +78,8 @@ describe('Policy Details', () => { let asyncActions: Promise = Promise.resolve(); beforeEach(() => { - policyPackageConfig = generator.generatePolicyPackageConfig(); - policyPackageConfig.id = '1'; + policyPackagePolicy = generator.generatePolicyPackagePolicy(); + policyPackagePolicy.id = '1'; const policyListApiHandlers = policyListApiPathHandlers(); @@ -87,15 +87,15 @@ describe('Policy Details', () => { const [path] = args; if (typeof path === 'string') { // GET datasouce - if (path === '/api/ingest_manager/package_configs/1') { + if (path === '/api/ingest_manager/package_policies/1') { asyncActions = asyncActions.then(async (): Promise => sleep()); return Promise.resolve({ - item: policyPackageConfig, + item: policyPackagePolicy, success: true, }); } - // GET Agent status for agent config + // GET Agent status for agent policy if (path === '/api/ingest_manager/fleet/agent-status') { asyncActions = asyncActions.then(async () => sleep()); return Promise.resolve({ @@ -132,7 +132,7 @@ describe('Policy Details', () => { const pageTitle = policyView.find('h1[data-test-subj="header-page-title"]'); expect(pageTitle).toHaveLength(1); - expect(pageTitle.text()).toEqual(policyPackageConfig.name); + expect(pageTitle.text()).toEqual(policyPackagePolicy.name); }); it('should navigate to list if back to link is clicked', async () => { policyView.update(); @@ -203,9 +203,9 @@ describe('Policy Details', () => { asyncActions = asyncActions.then(async () => sleep()); const [path] = args; if (typeof path === 'string') { - if (path === '/api/ingest_manager/package_configs/1') { + if (path === '/api/ingest_manager/package_policies/1') { return Promise.resolve({ - item: policyPackageConfig, + item: policyPackagePolicy, success: true, }); } @@ -229,7 +229,7 @@ describe('Policy Details', () => { ); expect(warningCallout).toHaveLength(1); expect(warningCallout.text()).toEqual( - 'This action will update 5 hostsSaving these changes will apply updates to all endpoints assigned to this agent configuration.' + 'This action will update 5 hostsSaving these changes will apply updates to all endpoints assigned to this agent policy.' ); }); it('should close dialog if cancel button is clicked', () => { @@ -248,7 +248,7 @@ describe('Policy Details', () => { // API should be called await asyncActions; - expect(http.put.mock.calls[0][0]).toEqual(`/api/ingest_manager/package_configs/1`); + expect(http.put.mock.calls[0][0]).toEqual(`/api/ingest_manager/package_policies/1`); policyView.update(); // Toast notification should be shown @@ -260,7 +260,7 @@ describe('Policy Details', () => { }); }); it('should show an error notification toast if update fails', async () => { - policyPackageConfig.id = 'invalid'; + policyPackagePolicy.id = 'invalid'; modalConfirmButton.simulate('click'); await asyncActions; diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.tsx index 636c0e5e6a0c3f..4135a4c595d6ac 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.tsx @@ -298,7 +298,7 @@ const ConfirmUpdate = React.memo<{ >
diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_list.test.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_list.test.tsx index b0139bf3ecb218..4fe7a496276f36 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_list.test.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_list.test.tsx @@ -52,7 +52,7 @@ describe.skip('when on the policies page', () => { middlewareSpy .waitForAction('serverReturnedPolicyListData') .then((action) => (firstPolicyID = action.payload.policyItems[0].id)), - // middlewareSpy.waitForAction('serverReturnedAgentConfigListData'), + // middlewareSpy.waitForAction('serverReturnedAgentPolicyListData'), ]); return renderResult; }; diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_list.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_list.tsx index b97ea958fd1c20..ff9c40675def80 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_list.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_list.tsx @@ -45,7 +45,7 @@ import { SecurityPageName } from '../../../../app/types'; import { useFormatUrl } from '../../../../common/components/link_to'; import { getPolicyDetailPath, getPoliciesPath } from '../../../common/routing'; import { useNavigateToAppEventHandler } from '../../../../common/hooks/endpoint/use_navigate_to_app_event_handler'; -import { CreatePackageConfigRouteState } from '../../../../../../ingest_manager/public'; +import { CreatePackagePolicyRouteState } from '../../../../../../ingest_manager/public'; import { MANAGEMENT_APP_ID } from '../../../common/constants'; import { AdministrationListPage } from '../../../components/administration_list_page'; @@ -145,7 +145,7 @@ export const PolicyList = React.memo(() => { endpointPackageVersion, } = usePolicyListSelector(selector); - const handleCreatePolicyClick = useNavigateToAppEventHandler( + const handleCreatePolicyClick = useNavigateToAppEventHandler( 'ingestManager', { // We redirect to Ingest's Integaration page if we can't get the package version, and @@ -221,11 +221,11 @@ export const PolicyList = React.memo(() => { ); const handleDeleteOnClick = useCallback( - ({ policyId, agentConfigId }: { policyId: string; agentConfigId: string }) => { + ({ policyId, agentPolicyId }: { policyId: string; agentPolicyId: string }) => { dispatch({ type: 'userOpenedPolicyListDeleteModal', payload: { - agentConfigId, + agentPolicyId, }, }); setPolicyIdToDelete(policyId); @@ -335,27 +335,27 @@ export const PolicyList = React.memo(() => { return ( + , { - handleDeleteOnClick({ agentConfigId: item.config_id, policyId: item.id }); + handleDeleteOnClick({ agentPolicyId: item.policy_id, policyId: item.id }); }} > { describe('ingest_integration sanity checks', () => { @@ -21,8 +21,8 @@ describe('ingest_integration tests ', () => { mockType: ManifestManagerMockType.InitialSystemState, }); - const callback = getPackageConfigCreateCallback(logger, manifestManager); - const policyConfig = createNewPackageConfigMock(); // policy config without manifest + const callback = getPackagePolicyCreateCallback(logger, manifestManager); + const policyConfig = createNewPackagePolicyMock(); // policy config without manifest const newPolicyConfig = await callback(policyConfig); // policy config WITH manifest expect(newPolicyConfig.inputs[0]!.type).toEqual('endpoint'); @@ -61,8 +61,8 @@ describe('ingest_integration tests ', () => { manifestManager.pushArtifacts = jest.fn().mockResolvedValue([new Error('error updating')]); const lastComputed = await manifestManager.getLastComputedManifest(); - const callback = getPackageConfigCreateCallback(logger, manifestManager); - const policyConfig = createNewPackageConfigMock(); + const callback = getPackagePolicyCreateCallback(logger, manifestManager); + const policyConfig = createNewPackagePolicyMock(); const newPolicyConfig = await callback(policyConfig); expect(newPolicyConfig.inputs[0]!.type).toEqual('endpoint'); @@ -81,8 +81,8 @@ describe('ingest_integration tests ', () => { expect(lastComputed).toEqual(null); manifestManager.buildNewManifest = jest.fn().mockRejectedValue(new Error('abcd')); - const callback = getPackageConfigCreateCallback(logger, manifestManager); - const policyConfig = createNewPackageConfigMock(); + const callback = getPackagePolicyCreateCallback(logger, manifestManager); + const policyConfig = createNewPackagePolicyMock(); const newPolicyConfig = await callback(policyConfig); expect(newPolicyConfig.inputs[0]!.type).toEqual('endpoint'); @@ -95,8 +95,8 @@ describe('ingest_integration tests ', () => { const lastComputed = await manifestManager.getLastComputedManifest(); manifestManager.buildNewManifest = jest.fn().mockResolvedValue(lastComputed); // no diffs - const callback = getPackageConfigCreateCallback(logger, manifestManager); - const policyConfig = createNewPackageConfigMock(); + const callback = getPackagePolicyCreateCallback(logger, manifestManager); + const policyConfig = createNewPackagePolicyMock(); const newPolicyConfig = await callback(policyConfig); expect(newPolicyConfig.inputs[0]!.type).toEqual('endpoint'); diff --git a/x-pack/plugins/security_solution/server/endpoint/ingest_integration.ts b/x-pack/plugins/security_solution/server/endpoint/ingest_integration.ts index 695267f3228579..489b146daeb432 100644 --- a/x-pack/plugins/security_solution/server/endpoint/ingest_integration.ts +++ b/x-pack/plugins/security_solution/server/endpoint/ingest_integration.ts @@ -5,7 +5,7 @@ */ import { Logger } from '../../../../../src/core/server'; -import { NewPackageConfig } from '../../../ingest_manager/common/types/models'; +import { NewPackagePolicy } from '../../../ingest_manager/common/types/models'; import { factory as policyConfigFactory } from '../../common/endpoint/models/policy_config'; import { NewPolicyData } from '../../common/endpoint/types'; import { ManifestManager } from './services/artifacts'; @@ -67,23 +67,23 @@ const getManifest = async (logger: Logger, manifestManager: ManifestManager): Pr }; /** - * Callback to handle creation of PackageConfigs in Ingest Manager + * Callback to handle creation of PackagePolicies in Ingest Manager */ -export const getPackageConfigCreateCallback = ( +export const getPackagePolicyCreateCallback = ( logger: Logger, manifestManager: ManifestManager -): ((newPackageConfig: NewPackageConfig) => Promise) => { - const handlePackageConfigCreate = async ( - newPackageConfig: NewPackageConfig - ): Promise => { - // We only care about Endpoint package configs - if (newPackageConfig.package?.name !== 'endpoint') { - return newPackageConfig; +): ((newPackagePolicy: NewPackagePolicy) => Promise) => { + const handlePackagePolicyCreate = async ( + newPackagePolicy: NewPackagePolicy + ): Promise => { + // We only care about Endpoint package policies + if (newPackagePolicy.package?.name !== 'endpoint') { + return newPackagePolicy; } // We cast the type here so that any changes to the Endpoint specific data // follow the types/schema expected - let updatedPackageConfig = newPackageConfig as NewPolicyData; + let updatedPackagePolicy = newPackagePolicy as NewPolicyData; // Get most recent manifest const manifest = await getManifest(logger, manifestManager); @@ -96,8 +96,8 @@ export const getPackageConfigCreateCallback = ( // Until we get the Default Policy Configuration in the Endpoint package, // we will add it here manually at creation time. - updatedPackageConfig = { - ...newPackageConfig, + updatedPackagePolicy = { + ...newPackagePolicy, inputs: [ { type: 'endpoint', @@ -115,8 +115,8 @@ export const getPackageConfigCreateCallback = ( ], }; - return updatedPackageConfig; + return updatedPackagePolicy; }; - return handlePackageConfigCreate; + return handlePackagePolicyCreate; }; diff --git a/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/mocks.ts b/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/mocks.ts index 62fff4715b562a..61850bfb3bc7d3 100644 --- a/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/mocks.ts +++ b/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/mocks.ts @@ -4,8 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { PackageConfig } from '../../../../../ingest_manager/common'; -import { createPackageConfigMock } from '../../../../../ingest_manager/common/mocks'; +import { PackagePolicy } from '../../../../../ingest_manager/common'; +import { createPackagePolicyMock } from '../../../../../ingest_manager/common/mocks'; import { InternalArtifactCompleteSchema } from '../../schemas/artifacts'; import { getInternalArtifactMock, @@ -69,9 +69,9 @@ export const getEmptyMockManifest = async (opts?: { compress: boolean }) => { return manifest; }; -export const createPackageConfigWithInitialManifestMock = (): PackageConfig => { - const packageConfig = createPackageConfigMock(); - packageConfig.inputs[0].config!.artifact_manifest = { +export const createPackagePolicyWithInitialManifestMock = (): PackagePolicy => { + const packagePolicy = createPackagePolicyMock(); + packagePolicy.inputs[0].config!.artifact_manifest = { value: { artifacts: { 'endpoint-exceptionlist-macos-v1': { @@ -99,12 +99,12 @@ export const createPackageConfigWithInitialManifestMock = (): PackageConfig => { schema_version: 'v1', }, }; - return packageConfig; + return packagePolicy; }; -export const createPackageConfigWithManifestMock = (): PackageConfig => { - const packageConfig = createPackageConfigMock(); - packageConfig.inputs[0].config!.artifact_manifest = { +export const createPackagePolicyWithManifestMock = (): PackagePolicy => { + const packagePolicy = createPackagePolicyMock(); + packagePolicy.inputs[0].config!.artifact_manifest = { value: { artifacts: { 'endpoint-exceptionlist-macos-v1': { @@ -133,5 +133,5 @@ export const createPackageConfigWithManifestMock = (): PackageConfig => { }, }; - return packageConfig; + return packagePolicy; }; diff --git a/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/task.ts b/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/task.ts index 4f2dbdf7644e2b..02e57a71dcd945 100644 --- a/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/task.ts +++ b/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/task.ts @@ -148,7 +148,7 @@ export class ManifestTask { } } - // Try dispatching to ingest-manager package configs + // Try dispatching to ingest-manager package policies const dispatchErrors = await manifestManager.tryDispatch(newManifest); if (dispatchErrors.length) { reportErrors(this.logger, dispatchErrors); diff --git a/x-pack/plugins/security_solution/server/endpoint/mocks.ts b/x-pack/plugins/security_solution/server/endpoint/mocks.ts index 9ca447d53bf45c..b5f35a198fa9e5 100644 --- a/x-pack/plugins/security_solution/server/endpoint/mocks.ts +++ b/x-pack/plugins/security_solution/server/endpoint/mocks.ts @@ -12,7 +12,7 @@ import { IngestManagerStartContract, ExternalCallback, } from '../../../ingest_manager/server'; -import { createPackageConfigServiceMock } from '../../../ingest_manager/server/mocks'; +import { createPackagePolicyServiceMock } from '../../../ingest_manager/server/mocks'; import { createMockConfig } from '../lib/detection_engine/routes/__mocks__'; import { EndpointAppContextService, @@ -96,7 +96,7 @@ export const createMockIngestManagerStartContract = ( }, agentService: createMockAgentService(), registerExternalCallback: jest.fn((...args: ExternalCallback) => {}), - packageConfigService: createPackageConfigServiceMock(), + packagePolicyService: createPackagePolicyServiceMock(), }; }; diff --git a/x-pack/plugins/security_solution/server/endpoint/services/artifacts/manifest_manager/manifest_manager.mock.ts b/x-pack/plugins/security_solution/server/endpoint/services/artifacts/manifest_manager/manifest_manager.mock.ts index 34e18c5fe85fc8..27dd38047e7c36 100644 --- a/x-pack/plugins/security_solution/server/endpoint/services/artifacts/manifest_manager/manifest_manager.mock.ts +++ b/x-pack/plugins/security_solution/server/endpoint/services/artifacts/manifest_manager/manifest_manager.mock.ts @@ -6,8 +6,8 @@ import { savedObjectsClientMock, loggingSystemMock } from 'src/core/server/mocks'; import { Logger } from 'src/core/server'; -import { PackageConfigServiceInterface } from '../../../../../../ingest_manager/server'; -import { createPackageConfigServiceMock } from '../../../../../../ingest_manager/server/mocks'; +import { PackagePolicyServiceInterface } from '../../../../../../ingest_manager/server'; +import { createPackagePolicyServiceMock } from '../../../../../../ingest_manager/server/mocks'; import { ExceptionListClient } from '../../../../../../lists/server'; import { listMock } from '../../../../../../lists/server/mocks'; import LRU from 'lru-cache'; @@ -15,8 +15,8 @@ import { getArtifactClientMock } from '../artifact_client.mock'; import { getManifestClientMock } from '../manifest_client.mock'; import { ManifestManager } from './manifest_manager'; import { - createPackageConfigWithManifestMock, - createPackageConfigWithInitialManifestMock, + createPackagePolicyWithManifestMock, + createPackagePolicyWithInitialManifestMock, getMockManifest, getMockArtifactsWithDiff, getEmptyMockArtifacts, @@ -32,7 +32,7 @@ export const getManifestManagerMock = (opts?: { mockType?: ManifestManagerMockType; cache?: LRU; exceptionListClient?: ExceptionListClient; - packageConfigService?: jest.Mocked; + packagePolicyService?: jest.Mocked; savedObjectsClient?: ReturnType; }): ManifestManager => { let cache = new LRU({ max: 10, maxAge: 1000 * 60 * 60 }); @@ -45,16 +45,16 @@ export const getManifestManagerMock = (opts?: { exceptionListClient = opts.exceptionListClient; } - let packageConfigService = createPackageConfigServiceMock(); - if (opts?.packageConfigService != null) { - packageConfigService = opts.packageConfigService; + let packagePolicyService = createPackagePolicyServiceMock(); + if (opts?.packagePolicyService != null) { + packagePolicyService = opts.packagePolicyService; } - packageConfigService.list = jest.fn().mockResolvedValue({ + packagePolicyService.list = jest.fn().mockResolvedValue({ total: 1, items: [ - { version: 'policy-1-version', ...createPackageConfigWithManifestMock() }, - { version: 'policy-2-version', ...createPackageConfigWithInitialManifestMock() }, - { version: 'policy-3-version', ...createPackageConfigWithInitialManifestMock() }, + { version: 'policy-1-version', ...createPackagePolicyWithManifestMock() }, + { version: 'policy-2-version', ...createPackagePolicyWithInitialManifestMock() }, + { version: 'policy-3-version', ...createPackagePolicyWithInitialManifestMock() }, ], }); @@ -97,7 +97,7 @@ export const getManifestManagerMock = (opts?: { const manifestManager = new ManifestManagerMock({ artifactClient: getArtifactClientMock(savedObjectsClient), cache, - packageConfigService, + packagePolicyService, exceptionListClient, logger: loggingSystemMock.create().get() as jest.Mocked, savedObjectsClient, diff --git a/x-pack/plugins/security_solution/server/endpoint/services/artifacts/manifest_manager/manifest_manager.test.ts b/x-pack/plugins/security_solution/server/endpoint/services/artifacts/manifest_manager/manifest_manager.test.ts index 8e0d55104fb7c5..bb6504de6e0a42 100644 --- a/x-pack/plugins/security_solution/server/endpoint/services/artifacts/manifest_manager/manifest_manager.test.ts +++ b/x-pack/plugins/security_solution/server/endpoint/services/artifacts/manifest_manager/manifest_manager.test.ts @@ -6,7 +6,7 @@ import { inflateSync } from 'zlib'; import { savedObjectsClientMock } from 'src/core/server/mocks'; -import { createPackageConfigServiceMock } from '../../../../../../ingest_manager/server/mocks'; +import { createPackagePolicyServiceMock } from '../../../../../../ingest_manager/server/mocks'; import { ArtifactConstants, ManifestConstants, isCompleteArtifact } from '../../../lib/artifacts'; import { getManifestManagerMock, ManifestManagerMockType } from './manifest_manager.mock'; @@ -92,8 +92,8 @@ describe('manifest_manager', () => { }); test('ManifestManager cannot dispatch incomplete (uncompressed) artifact', async () => { - const packageConfigService = createPackageConfigServiceMock(); - const manifestManager = getManifestManagerMock({ packageConfigService }); + const packagePolicyService = createPackagePolicyServiceMock(); + const manifestManager = getManifestManagerMock({ packagePolicyService }); const oldManifest = await manifestManager.getLastComputedManifest(); const newManifest = await manifestManager.buildNewManifest(oldManifest!); const dispatchErrors = await manifestManager.tryDispatch(newManifest); @@ -102,8 +102,8 @@ describe('manifest_manager', () => { }); test('ManifestManager can dispatch manifest', async () => { - const packageConfigService = createPackageConfigServiceMock(); - const manifestManager = getManifestManagerMock({ packageConfigService }); + const packagePolicyService = createPackagePolicyServiceMock(); + const manifestManager = getManifestManagerMock({ packagePolicyService }); const oldManifest = await manifestManager.getLastComputedManifest(); const newManifest = await manifestManager.buildNewManifest(oldManifest!); const diffs = newManifest.diff(oldManifest!); @@ -117,10 +117,10 @@ describe('manifest_manager', () => { expect(dispatchErrors).toEqual([]); // 2 policies updated... 1 is already up-to-date - expect(packageConfigService.update.mock.calls.length).toEqual(2); + expect(packagePolicyService.update.mock.calls.length).toEqual(2); expect( - packageConfigService.update.mock.calls[0][2].inputs[0].config!.artifact_manifest.value + packagePolicyService.update.mock.calls[0][2].inputs[0].config!.artifact_manifest.value ).toEqual({ manifest_version: '1.0.1', schema_version: 'v1', @@ -150,8 +150,8 @@ describe('manifest_manager', () => { }); test('ManifestManager fails to dispatch on conflict', async () => { - const packageConfigService = createPackageConfigServiceMock(); - const manifestManager = getManifestManagerMock({ packageConfigService }); + const packagePolicyService = createPackagePolicyServiceMock(); + const manifestManager = getManifestManagerMock({ packagePolicyService }); const oldManifest = await manifestManager.getLastComputedManifest(); const newManifest = await manifestManager.buildNewManifest(oldManifest!); const diffs = newManifest.diff(oldManifest!); @@ -160,7 +160,7 @@ describe('manifest_manager', () => { newManifest.bumpSemanticVersion(); - packageConfigService.update.mockRejectedValueOnce({ status: 409 }); + packagePolicyService.update.mockRejectedValueOnce({ status: 409 }); const dispatchErrors = await manifestManager.tryDispatch(newManifest); expect(dispatchErrors).toEqual([{ status: 409 }]); }); diff --git a/x-pack/plugins/security_solution/server/endpoint/services/artifacts/manifest_manager/manifest_manager.ts b/x-pack/plugins/security_solution/server/endpoint/services/artifacts/manifest_manager/manifest_manager.ts index 9d15b4464c1917..70557886e57c51 100644 --- a/x-pack/plugins/security_solution/server/endpoint/services/artifacts/manifest_manager/manifest_manager.ts +++ b/x-pack/plugins/security_solution/server/endpoint/services/artifacts/manifest_manager/manifest_manager.ts @@ -6,7 +6,7 @@ import semver from 'semver'; import { Logger, SavedObjectsClientContract } from 'src/core/server'; import LRU from 'lru-cache'; -import { PackageConfigServiceInterface } from '../../../../../../ingest_manager/server'; +import { PackagePolicyServiceInterface } from '../../../../../../ingest_manager/server'; import { ExceptionListClient } from '../../../../../../lists/server'; import { ManifestSchemaVersion } from '../../../../../common/endpoint/schema/common'; import { manifestDispatchSchema } from '../../../../../common/endpoint/schema/manifest'; @@ -30,7 +30,7 @@ export interface ManifestManagerContext { savedObjectsClient: SavedObjectsClientContract; artifactClient: ArtifactClient; exceptionListClient: ExceptionListClient; - packageConfigService: PackageConfigServiceInterface; + packagePolicyService: PackagePolicyServiceInterface; logger: Logger; cache: LRU; } @@ -47,7 +47,7 @@ export interface ManifestSnapshot { export class ManifestManager { protected artifactClient: ArtifactClient; protected exceptionListClient: ExceptionListClient; - protected packageConfigService: PackageConfigServiceInterface; + protected packagePolicyService: PackagePolicyServiceInterface; protected savedObjectsClient: SavedObjectsClientContract; protected logger: Logger; protected cache: LRU; @@ -56,7 +56,7 @@ export class ManifestManager { constructor(context: ManifestManagerContext) { this.artifactClient = context.artifactClient; this.exceptionListClient = context.exceptionListClient; - this.packageConfigService = context.packageConfigService; + this.packagePolicyService = context.packagePolicyService; this.savedObjectsClient = context.savedObjectsClient; this.logger = context.logger; this.cache = context.cache; @@ -217,7 +217,7 @@ export class ManifestManager { } /** - * Dispatches the manifest by writing it to the endpoint package config, if different + * Dispatches the manifest by writing it to the endpoint package policy, if different * from the manifest already in the config. * * @param manifest The Manifest to dispatch. @@ -234,39 +234,39 @@ export class ManifestManager { const errors: Error[] = []; while (paging) { - const { items, total } = await this.packageConfigService.list(this.savedObjectsClient, { + const { items, total } = await this.packagePolicyService.list(this.savedObjectsClient, { page, perPage: 20, kuery: 'ingest-package-policies.package.name:endpoint', }); - for (const packageConfig of items) { + for (const packagePolicy of items) { // eslint-disable-next-line @typescript-eslint/naming-convention - const { id, revision, updated_at, updated_by, ...newPackageConfig } = packageConfig; - if (newPackageConfig.inputs.length > 0 && newPackageConfig.inputs[0].config !== undefined) { - const oldManifest = newPackageConfig.inputs[0].config.artifact_manifest ?? { + const { id, revision, updated_at, updated_by, ...newPackagePolicy } = packagePolicy; + if (newPackagePolicy.inputs.length > 0 && newPackagePolicy.inputs[0].config !== undefined) { + const oldManifest = newPackagePolicy.inputs[0].config.artifact_manifest ?? { value: {}, }; const newManifestVersion = manifest.getSemanticVersion(); if (semver.gt(newManifestVersion, oldManifest.value.manifest_version)) { - newPackageConfig.inputs[0].config.artifact_manifest = { + newPackagePolicy.inputs[0].config.artifact_manifest = { value: serializedManifest, }; try { - await this.packageConfigService.update(this.savedObjectsClient, id, newPackageConfig); + await this.packagePolicyService.update(this.savedObjectsClient, id, newPackagePolicy); this.logger.debug( - `Updated package config ${id} with manifest version ${manifest.getSemanticVersion()}` + `Updated package policy ${id} with manifest version ${manifest.getSemanticVersion()}` ); } catch (err) { errors.push(err); } } else { - this.logger.debug(`No change in package config: ${id}`); + this.logger.debug(`No change in package policy: ${id}`); } } else { - errors.push(new Error(`Package config ${id} has no config.`)); + errors.push(new Error(`Package Policy ${id} has no config.`)); } } paging = (page - 1) * 20 + items.length < total; diff --git a/x-pack/plugins/security_solution/server/plugin.ts b/x-pack/plugins/security_solution/server/plugin.ts index f2fad16d80414c..85764eaaee32d6 100644 --- a/x-pack/plugins/security_solution/server/plugin.ts +++ b/x-pack/plugins/security_solution/server/plugin.ts @@ -285,7 +285,7 @@ export class Plugin implements IPlugin { - describe('POST /api/ingest_manager/agent_configs', () => { + describe('ingest_manager_agent_policies', () => { + describe('POST /api/ingest_manager/agent_policies', () => { it('should work with valid values', async () => { const { body: apiResponse } = await supertest - .post(`/api/ingest_manager/agent_configs`) + .post(`/api/ingest_manager/agent_policies`) .set('kbn-xsrf', 'xxxx') .send({ name: 'TEST', @@ -28,7 +28,7 @@ export default function ({ getService }: FtrProviderContext) { it('should return a 400 with an invalid namespace', async () => { await supertest - .post(`/api/ingest_manager/agent_configs`) + .post(`/api/ingest_manager/agent_policies`) .set('kbn-xsrf', 'xxxx') .send({ name: 'TEST', @@ -38,7 +38,7 @@ export default function ({ getService }: FtrProviderContext) { }); }); - describe('POST /api/ingest_manager/agent_configs/{agentConfigId}/copy', () => { + describe('POST /api/ingest_manager/agent_policies/{agentPolicyId}/copy', () => { before(async () => { await esArchiver.loadIfNeeded('fleet/agents'); }); @@ -46,40 +46,40 @@ export default function ({ getService }: FtrProviderContext) { await esArchiver.unload('fleet/agents'); }); - const TEST_CONFIG_ID = 'config1'; + const TEST_POLICY_ID = 'policy1'; it('should work with valid values', async () => { const { body: { success, item }, } = await supertest - .post(`/api/ingest_manager/agent_configs/${TEST_CONFIG_ID}/copy`) + .post(`/api/ingest_manager/agent_policies/${TEST_POLICY_ID}/copy`) .set('kbn-xsrf', 'xxxx') .send({ - name: 'Copied config', + name: 'Copied policy', description: 'Test', }) .expect(200); // eslint-disable-next-line @typescript-eslint/naming-convention - const { id, updated_at, ...newConfig } = item; + const { id, updated_at, ...newPolicy } = item; expect(success).to.be(true); - expect(newConfig).to.eql({ - name: 'Copied config', + expect(newPolicy).to.eql({ + name: 'Copied policy', description: 'Test', namespace: 'default', monitoring_enabled: ['logs', 'metrics'], revision: 1, updated_by: 'elastic', - package_configs: [], + package_policies: [], }); }); - it('should return a 500 with invalid source config', async () => { + it('should return a 500 with invalid source policy', async () => { await supertest - .post(`/api/ingest_manager/agent_configs/INVALID_CONFIG_ID/copy`) + .post(`/api/ingest_manager/agent_policies/INVALID_POLICY_ID/copy`) .set('kbn-xsrf', 'xxxx') .send({ - name: 'Copied config', + name: 'Copied policy', description: '', }) .expect(500); @@ -87,7 +87,7 @@ export default function ({ getService }: FtrProviderContext) { it('should return a 400 with invalid payload', async () => { await supertest - .post(`/api/ingest_manager/agent_configs/${TEST_CONFIG_ID}/copy`) + .post(`/api/ingest_manager/agent_policies/${TEST_POLICY_ID}/copy`) .set('kbn-xsrf', 'xxxx') .send({}) .expect(400); @@ -95,7 +95,7 @@ export default function ({ getService }: FtrProviderContext) { it('should return a 400 with invalid name', async () => { await supertest - .post(`/api/ingest_manager/agent_configs/${TEST_CONFIG_ID}/copy`) + .post(`/api/ingest_manager/agent_policies/${TEST_POLICY_ID}/copy`) .set('kbn-xsrf', 'xxxx') .send({ name: '', diff --git a/x-pack/test/ingest_manager_api_integration/apis/agent_config/index.js b/x-pack/test/ingest_manager_api_integration/apis/agent_policy/index.js similarity index 86% rename from x-pack/test/ingest_manager_api_integration/apis/agent_config/index.js rename to x-pack/test/ingest_manager_api_integration/apis/agent_policy/index.js index 1671c423c03c0f..a513e7991fa741 100644 --- a/x-pack/test/ingest_manager_api_integration/apis/agent_config/index.js +++ b/x-pack/test/ingest_manager_api_integration/apis/agent_policy/index.js @@ -6,6 +6,6 @@ export default function loadTests({ loadTestFile }) { describe('Ingest Manager Endpoints', () => { - loadTestFile(require.resolve('./agent_config')); + loadTestFile(require.resolve('./agent_policy')); }); } diff --git a/x-pack/test/ingest_manager_api_integration/apis/fleet/agents/complete_flow.ts b/x-pack/test/ingest_manager_api_integration/apis/fleet/agents/complete_flow.ts index 8d7472f0ecd8b2..2d14a7a10e6685 100644 --- a/x-pack/test/ingest_manager_api_integration/apis/fleet/agents/complete_flow.ts +++ b/x-pack/test/ingest_manager_api_integration/apis/fleet/agents/complete_flow.ts @@ -79,8 +79,8 @@ export default function (providerContext: FtrProviderContext) { expect(checkinApiResponse.success).to.eql(true); expect(checkinApiResponse.actions).length(1); expect(checkinApiResponse.actions[0].type).be('CONFIG_CHANGE'); - const configChangeAction = checkinApiResponse.actions[0]; - const defaultOutputApiKey = configChangeAction.data.config.outputs.default.api_key; + const policyChangeAction = checkinApiResponse.actions[0]; + const defaultOutputApiKey = policyChangeAction.data.config.outputs.default.api_key; // Ack actions const { body: ackApiResponse } = await supertestWithoutAuth @@ -94,7 +94,7 @@ export default function (providerContext: FtrProviderContext) { type: 'ACTION_RESULT', subtype: 'ACKNOWLEDGED', timestamp: '2019-01-04T14:32:03.36764-05:00', - action_id: configChangeAction.id, + action_id: policyChangeAction.id, agent_id: enrollmentResponse.item.id, message: 'hello', payload: 'payload', diff --git a/x-pack/test/ingest_manager_api_integration/apis/fleet/agents/enroll.ts b/x-pack/test/ingest_manager_api_integration/apis/fleet/agents/enroll.ts index ef9f2b2e61500b..ce356dbd081c88 100644 --- a/x-pack/test/ingest_manager_api_integration/apis/fleet/agents/enroll.ts +++ b/x-pack/test/ingest_manager_api_integration/apis/fleet/agents/enroll.ts @@ -137,7 +137,7 @@ export default function (providerContext: FtrProviderContext) { }) .expect(200); expect(apiResponse.success).to.eql(true); - expect(apiResponse.item).to.have.keys('id', 'active', 'access_api_key', 'type', 'config_id'); + expect(apiResponse.item).to.have.keys('id', 'active', 'access_api_key', 'type', 'policy_id'); }); it('when enrolling an agent it should generate an access api key with limited privileges', async () => { diff --git a/x-pack/test/ingest_manager_api_integration/apis/fleet/enrollment_api_keys/crud.ts b/x-pack/test/ingest_manager_api_integration/apis/fleet/enrollment_api_keys/crud.ts index bc9182627326b9..275462072919bb 100644 --- a/x-pack/test/ingest_manager_api_integration/apis/fleet/enrollment_api_keys/crud.ts +++ b/x-pack/test/ingest_manager_api_integration/apis/fleet/enrollment_api_keys/crud.ts @@ -59,7 +59,7 @@ export default function (providerContext: FtrProviderContext) { .post(`/api/ingest_manager/fleet/enrollment-api-keys`) .set('kbn-xsrf', 'xxx') .send({ - config_id: 'config1', + policy_id: 'policy1', }) .expect(200); keyId = apiResponse.item.id; @@ -94,27 +94,27 @@ export default function (providerContext: FtrProviderContext) { .expect(400); }); - it('should not allow to create an enrollment api key for a non existing agent config', async () => { + it('should not allow to create an enrollment api key for a non existing agent policy', async () => { await supertest .post(`/api/ingest_manager/fleet/enrollment-api-keys`) .set('kbn-xsrf', 'xxx') .send({ - config_id: 'idonotexistsconfig', + policy_id: 'idonotexistspolicy', }) .expect(400); }); - it('should allow to create an enrollment api key with an agent config', async () => { + it('should allow to create an enrollment api key with an agent policy', async () => { const { body: apiResponse } = await supertest .post(`/api/ingest_manager/fleet/enrollment-api-keys`) .set('kbn-xsrf', 'xxx') .send({ - config_id: 'config1', + policy_id: 'policy1', }) .expect(200); expect(apiResponse.success).to.eql(true); - expect(apiResponse.item).to.have.keys('id', 'api_key', 'api_key_id', 'name', 'config_id'); + expect(apiResponse.item).to.have.keys('id', 'api_key', 'api_key_id', 'name', 'policy_id'); }); it('should create an ES ApiKey with limited privileges', async () => { @@ -122,7 +122,7 @@ export default function (providerContext: FtrProviderContext) { .post(`/api/ingest_manager/fleet/enrollment-api-keys`) .set('kbn-xsrf', 'xxx') .send({ - config_id: 'config1', + policy_id: 'policy1', }) .expect(200); expect(apiResponse.success).to.eql(true); diff --git a/x-pack/test/ingest_manager_api_integration/apis/index.js b/x-pack/test/ingest_manager_api_integration/apis/index.js index 948f953ebe3f5f..fac8a26fd6aec4 100644 --- a/x-pack/test/ingest_manager_api_integration/apis/index.js +++ b/x-pack/test/ingest_manager_api_integration/apis/index.js @@ -15,11 +15,12 @@ export default function ({ loadTestFile }) { // EPM loadTestFile(require.resolve('./epm/index')); - // Package configs - loadTestFile(require.resolve('./package_config/create')); - loadTestFile(require.resolve('./package_config/update')); - loadTestFile(require.resolve('./package_config/get')); - // Agent config - loadTestFile(require.resolve('./agent_config/index')); + // Package policies + loadTestFile(require.resolve('./package_policy/create')); + loadTestFile(require.resolve('./package_policy/update')); + loadTestFile(require.resolve('./package_policy/get')); + + // Agent policies + loadTestFile(require.resolve('./agent_policy/index')); }); } diff --git a/x-pack/test/ingest_manager_api_integration/apis/package_config/create.ts b/x-pack/test/ingest_manager_api_integration/apis/package_policy/create.ts similarity index 81% rename from x-pack/test/ingest_manager_api_integration/apis/package_config/create.ts rename to x-pack/test/ingest_manager_api_integration/apis/package_policy/create.ts index a2c2b99364d509..2043faa07b1e11 100644 --- a/x-pack/test/ingest_manager_api_integration/apis/package_config/create.ts +++ b/x-pack/test/ingest_manager_api_integration/apis/package_policy/create.ts @@ -18,30 +18,30 @@ export default function ({ getService }: FtrProviderContext) { // because `this` has to point to the Mocha context // see https://mochajs.org/#arrow-functions - describe('Package Config - create', async function () { - let agentConfigId: string; + describe('Package Policy - create', async function () { + let agentPolicyId: string; before(async function () { - const { body: agentConfigResponse } = await supertest - .post(`/api/ingest_manager/agent_configs`) + const { body: agentPolicyResponse } = await supertest + .post(`/api/ingest_manager/agent_policies`) .set('kbn-xsrf', 'xxxx') .send({ - name: 'Test config', + name: 'Test policy', namespace: 'default', }); - agentConfigId = agentConfigResponse.item.id; + agentPolicyId = agentPolicyResponse.item.id; }); it('should work with valid values', async function () { if (server.enabled) { const { body: apiResponse } = await supertest - .post(`/api/ingest_manager/package_configs`) + .post(`/api/ingest_manager/package_policies`) .set('kbn-xsrf', 'xxxx') .send({ name: 'filetest-1', description: '', namespace: 'default', - config_id: agentConfigId, + policy_id: agentPolicyId, enabled: true, output_id: '', inputs: [], @@ -62,13 +62,13 @@ export default function ({ getService }: FtrProviderContext) { it('should return a 400 with an invalid namespace', async function () { if (server.enabled) { await supertest - .post(`/api/ingest_manager/package_configs`) + .post(`/api/ingest_manager/package_policies`) .set('kbn-xsrf', 'xxxx') .send({ name: 'filetest-1', description: '', namespace: '', - config_id: agentConfigId, + policy_id: agentPolicyId, enabled: true, output_id: '', inputs: [], @@ -84,16 +84,16 @@ export default function ({ getService }: FtrProviderContext) { } }); - it('should not allow multiple limited packages on the same agent config', async function () { + it('should not allow multiple limited packages on the same agent policy', async function () { if (server.enabled) { await supertest - .post(`/api/ingest_manager/package_configs`) + .post(`/api/ingest_manager/package_policies`) .set('kbn-xsrf', 'xxxx') .send({ name: 'endpoint-1', description: '', namespace: 'default', - config_id: agentConfigId, + policy_id: agentPolicyId, enabled: true, output_id: '', inputs: [], @@ -105,13 +105,13 @@ export default function ({ getService }: FtrProviderContext) { }) .expect(200); await supertest - .post(`/api/ingest_manager/package_configs`) + .post(`/api/ingest_manager/package_policies`) .set('kbn-xsrf', 'xxxx') .send({ name: 'endpoint-2', description: '', namespace: 'default', - config_id: agentConfigId, + policy_id: agentPolicyId, enabled: true, output_id: '', inputs: [], @@ -127,16 +127,16 @@ export default function ({ getService }: FtrProviderContext) { } }); - it('should return a 500 if there is another package config with the same name', async function () { + it('should return a 500 if there is another package policy with the same name', async function () { if (server.enabled) { await supertest - .post(`/api/ingest_manager/package_configs`) + .post(`/api/ingest_manager/package_policies`) .set('kbn-xsrf', 'xxxx') .send({ name: 'same-name-test-1', description: '', namespace: 'default', - config_id: agentConfigId, + policy_id: agentPolicyId, enabled: true, output_id: '', inputs: [], @@ -148,13 +148,13 @@ export default function ({ getService }: FtrProviderContext) { }) .expect(200); await supertest - .post(`/api/ingest_manager/package_configs`) + .post(`/api/ingest_manager/package_policies`) .set('kbn-xsrf', 'xxxx') .send({ name: 'same-name-test-1', description: '', namespace: 'default', - config_id: agentConfigId, + policy_id: agentPolicyId, enabled: true, output_id: '', inputs: [], diff --git a/x-pack/test/ingest_manager_api_integration/apis/package_config/get.ts b/x-pack/test/ingest_manager_api_integration/apis/package_policy/get.ts similarity index 68% rename from x-pack/test/ingest_manager_api_integration/apis/package_config/get.ts rename to x-pack/test/ingest_manager_api_integration/apis/package_policy/get.ts index 94b7543d982add..756eaa8ea49bab 100644 --- a/x-pack/test/ingest_manager_api_integration/apis/package_config/get.ts +++ b/x-pack/test/ingest_manager_api_integration/apis/package_policy/get.ts @@ -18,32 +18,32 @@ export default function (providerContext: FtrProviderContext) { // because `this` has to point to the Mocha context // see https://mochajs.org/#arrow-functions - describe('Package Config - get by id', async function () { + describe('Package Policy - get by id', async function () { skipIfNoDockerRegistry(providerContext); - let agentConfigId: string; - let packageConfigId: string; + let agentPolicyId: string; + let packagePolicyId: string; before(async function () { if (!server.enabled) { return; } - const { body: agentConfigResponse } = await supertest - .post(`/api/ingest_manager/agent_configs`) + const { body: agentPolicyResponse } = await supertest + .post(`/api/ingest_manager/agent_policies`) .set('kbn-xsrf', 'xxxx') .send({ - name: 'Test config', + name: 'Test policy', namespace: 'default', }); - agentConfigId = agentConfigResponse.item.id; + agentPolicyId = agentPolicyResponse.item.id; - const { body: packageConfigResponse } = await supertest - .post(`/api/ingest_manager/package_configs`) + const { body: packagePolicyResponse } = await supertest + .post(`/api/ingest_manager/package_policies`) .set('kbn-xsrf', 'xxxx') .send({ name: 'filetest-1', description: '', namespace: 'default', - config_id: agentConfigId, + policy_id: agentPolicyId, enabled: true, output_id: '', inputs: [], @@ -53,7 +53,7 @@ export default function (providerContext: FtrProviderContext) { version: '0.1.0', }, }); - packageConfigId = packageConfigResponse.item.id; + packagePolicyId = packagePolicyResponse.item.id; }); after(async function () { @@ -62,28 +62,28 @@ export default function (providerContext: FtrProviderContext) { } await supertest - .post(`/api/ingest_manager/agent_configs/delete`) + .post(`/api/ingest_manager/agent_policies/delete`) .set('kbn-xsrf', 'xxxx') - .send({ agentConfigId }) + .send({ agentPolicyId }) .expect(200); await supertest - .post(`/api/ingest_manager/package_configs/delete`) + .post(`/api/ingest_manager/package_policies/delete`) .set('kbn-xsrf', 'xxxx') - .send({ packageConfigIds: [packageConfigId] }) + .send({ packagePolicyIds: [packagePolicyId] }) .expect(200); }); it('should succeed with a valid id', async function () { const { body: apiResponse } = await supertest - .get(`/api/ingest_manager/package_configs/${packageConfigId}`) + .get(`/api/ingest_manager/package_policies/${packagePolicyId}`) .expect(200); expect(apiResponse.success).to.be(true); }); it('should return a 404 with an invalid id', async function () { - await supertest.get(`/api/ingest_manager/package_configs/IS_NOT_PRESENT`).expect(404); + await supertest.get(`/api/ingest_manager/package_policies/IS_NOT_PRESENT`).expect(404); }); }); } diff --git a/x-pack/test/ingest_manager_api_integration/apis/package_config/update.ts b/x-pack/test/ingest_manager_api_integration/apis/package_policy/update.ts similarity index 72% rename from x-pack/test/ingest_manager_api_integration/apis/package_config/update.ts rename to x-pack/test/ingest_manager_api_integration/apis/package_policy/update.ts index 7b0ad4f524bad6..e74d88f3538e4a 100644 --- a/x-pack/test/ingest_manager_api_integration/apis/package_config/update.ts +++ b/x-pack/test/ingest_manager_api_integration/apis/package_policy/update.ts @@ -18,33 +18,33 @@ export default function (providerContext: FtrProviderContext) { // because `this` has to point to the Mocha context // see https://mochajs.org/#arrow-functions - describe('Package Config - update', async function () { + describe('Package Policy - update', async function () { skipIfNoDockerRegistry(providerContext); - let agentConfigId: string; - let packageConfigId: string; - let packageConfigId2: string; + let agentPolicyId: string; + let packagePolicyId: string; + let packagePolicyId2: string; before(async function () { if (!server.enabled) { return; } - const { body: agentConfigResponse } = await supertest - .post(`/api/ingest_manager/agent_configs`) + const { body: agentPolicyResponse } = await supertest + .post(`/api/ingest_manager/agent_policies`) .set('kbn-xsrf', 'xxxx') .send({ - name: 'Test config', + name: 'Test policy', namespace: 'default', }); - agentConfigId = agentConfigResponse.item.id; + agentPolicyId = agentPolicyResponse.item.id; - const { body: packageConfigResponse } = await supertest - .post(`/api/ingest_manager/package_configs`) + const { body: packagePolicyResponse } = await supertest + .post(`/api/ingest_manager/package_policies`) .set('kbn-xsrf', 'xxxx') .send({ name: 'filetest-1', description: '', namespace: 'default', - config_id: agentConfigId, + policy_id: agentPolicyId, enabled: true, output_id: '', inputs: [], @@ -54,16 +54,16 @@ export default function (providerContext: FtrProviderContext) { version: '0.1.0', }, }); - packageConfigId = packageConfigResponse.item.id; + packagePolicyId = packagePolicyResponse.item.id; - const { body: packageConfigResponse2 } = await supertest - .post(`/api/ingest_manager/package_configs`) + const { body: packagePolicyResponse2 } = await supertest + .post(`/api/ingest_manager/package_policies`) .set('kbn-xsrf', 'xxxx') .send({ name: 'filetest-2', description: '', namespace: 'default', - config_id: agentConfigId, + policy_id: agentPolicyId, enabled: true, output_id: '', inputs: [], @@ -73,18 +73,18 @@ export default function (providerContext: FtrProviderContext) { version: '0.1.0', }, }); - packageConfigId2 = packageConfigResponse2.item.id; + packagePolicyId2 = packagePolicyResponse2.item.id; }); it('should work with valid values', async function () { const { body: apiResponse } = await supertest - .put(`/api/ingest_manager/package_configs/${packageConfigId}`) + .put(`/api/ingest_manager/package_policies/${packagePolicyId}`) .set('kbn-xsrf', 'xxxx') .send({ name: 'filetest-1', description: '', namespace: 'updated_namespace', - config_id: agentConfigId, + policy_id: agentPolicyId, enabled: true, output_id: '', inputs: [], @@ -99,15 +99,15 @@ export default function (providerContext: FtrProviderContext) { expect(apiResponse.success).to.be(true); }); - it('should return a 500 if there is another package config with the same name', async function () { + it('should return a 500 if there is another package policy with the same name', async function () { await supertest - .put(`/api/ingest_manager/package_configs/${packageConfigId2}`) + .put(`/api/ingest_manager/package_policies/${packagePolicyId2}`) .set('kbn-xsrf', 'xxxx') .send({ name: 'filetest-1', description: '', namespace: 'updated_namespace', - config_id: agentConfigId, + policy_id: agentPolicyId, enabled: true, output_id: '', inputs: [], diff --git a/x-pack/test/security_solution_cypress/es_archives/export_rule/mappings.json b/x-pack/test/security_solution_cypress/es_archives/export_rule/mappings.json index 249b03981386d3..5eec03ca3d11a8 100644 --- a/x-pack/test/security_solution_cypress/es_archives/export_rule/mappings.json +++ b/x-pack/test/security_solution_cypress/es_archives/export_rule/mappings.json @@ -970,7 +970,7 @@ "agent_id": { "type": "keyword" }, - "config_id": { + "policy_id": { "type": "keyword" }, "data": { @@ -1004,7 +1004,7 @@ "active": { "type": "boolean" }, - "config_id": { + "policy_id": { "type": "keyword" }, "config_revision": { @@ -1072,7 +1072,7 @@ "api_key_id": { "type": "keyword" }, - "config_id": { + "policy_id": { "type": "keyword" }, "created_at": { @@ -1240,7 +1240,7 @@ "namespace": { "type": "keyword" }, - "package_configs": { + "package_policies": { "type": "keyword" }, "revision": { @@ -1288,7 +1288,7 @@ }, "ingest-package-policies": { "properties": { - "config_id": { + "policy_id": { "type": "keyword" }, "created_at": { diff --git a/x-pack/test/security_solution_endpoint/apps/endpoint/endpoint_list.ts b/x-pack/test/security_solution_endpoint/apps/endpoint/endpoint_list.ts index 1843fca29758a3..6268f55c5518c3 100644 --- a/x-pack/test/security_solution_endpoint/apps/endpoint/endpoint_list.ts +++ b/x-pack/test/security_solution_endpoint/apps/endpoint/endpoint_list.ts @@ -125,7 +125,7 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { }); // The integration does not work properly yet. Skipping this test for now. - it.skip('navigates to ingest fleet when the Reassign Configuration link is clicked', async () => { + it.skip('navigates to ingest fleet when the Reassign Policy link is clicked', async () => { await (await testSubjects.find('hostnameCellLink')).click(); await (await testSubjects.find('endpointDetailsLinkToIngest')).click(); await testSubjects.existOrFail('fleetAgentListTable'); diff --git a/x-pack/test/security_solution_endpoint/apps/endpoint/policy_details.ts b/x-pack/test/security_solution_endpoint/apps/endpoint/policy_details.ts index 9efba2b595bde6..3e04a507d3810f 100644 --- a/x-pack/test/security_solution_endpoint/apps/endpoint/policy_details.ts +++ b/x-pack/test/security_solution_endpoint/apps/endpoint/policy_details.ts @@ -14,7 +14,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { 'endpoint', 'policy', 'endpointPageUtils', - 'ingestManagerCreatePackageConfig', + 'ingestManagerCreatePackagePolicy', ]); const testSubjects = getService('testSubjects'); const policyTestResources = getService('policyTestResources'); @@ -27,7 +27,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { await pageObjects.policy.navigateToPolicyDetails('invalid-id'); await testSubjects.existOrFail('policyDetailsIdNotFoundMessage'); expect(await testSubjects.getVisibleText('policyDetailsIdNotFoundMessage')).to.equal( - 'Package config invalid-id not found' + 'Package policy invalid-id not found' ); }); }); @@ -37,7 +37,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { before(async () => { policyInfo = await policyTestResources.createPolicy(); - await pageObjects.policy.navigateToPolicyDetails(policyInfo.packageConfig.id); + await pageObjects.policy.navigateToPolicyDetails(policyInfo.packagePolicy.id); }); after(async () => { @@ -48,7 +48,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { it('should display policy view', async () => { expect(await testSubjects.getVisibleText('header-page-title')).to.equal( - policyInfo.packageConfig.name + policyInfo.packagePolicy.name ); }); }); @@ -58,7 +58,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { beforeEach(async () => { policyInfo = await policyTestResources.createPolicy(); - await pageObjects.policy.navigateToPolicyDetails(policyInfo.packageConfig.id); + await pageObjects.policy.navigateToPolicyDetails(policyInfo.packagePolicy.id); }); afterEach(async () => { @@ -73,7 +73,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { await testSubjects.existOrFail('policyDetailsSuccessMessage'); expect(await testSubjects.getVisibleText('policyDetailsSuccessMessage')).to.equal( - `Integration ${policyInfo.packageConfig.name} has been updated.` + `Integration ${policyInfo.packagePolicy.name} has been updated.` ); }); it('should persist update on the screen', async () => { @@ -82,15 +82,15 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { await testSubjects.existOrFail('policyDetailsSuccessMessage'); await pageObjects.endpoint.navigateToEndpointList(); - await pageObjects.policy.navigateToPolicyDetails(policyInfo.packageConfig.id); + await pageObjects.policy.navigateToPolicyDetails(policyInfo.packagePolicy.id); expect(await (await testSubjects.find('policyWindowsEvent_process')).isSelected()).to.equal( false ); }); - it('should have updated policy data in overall agent configuration', async () => { + it('should have updated policy data in overall Agent Policy', async () => { // This test ensures that updates made to the Endpoint Policy are carried all the way through - // to the generated Agent Configuration that is dispatch down to the Elastic Agent. + // to the generated Agent Policy that is dispatch down to the Elastic Agent. await Promise.all([ pageObjects.endpointPageUtils.clickOnEuiCheckbox('policyWindowsEvent_file'), @@ -100,14 +100,14 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { await pageObjects.policy.confirmAndSave(); await testSubjects.existOrFail('policyDetailsSuccessMessage'); - const agentFullConfig = await policyTestResources.getFullAgentConfig( - policyInfo.agentConfig.id + const agentFullPolicy = await policyTestResources.getFullAgentPolicy( + policyInfo.agentPolicy.id ); - expect(agentFullConfig).to.eql({ + expect(agentFullPolicy).to.eql({ inputs: [ { - id: policyInfo.packageConfig.id, + id: policyInfo.packagePolicy.id, data_stream: { namespace: 'default' }, name: 'Protect East Coast', meta: { @@ -145,9 +145,9 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { }, // The manifest version could have changed when the Policy was updated because the // policy details page ensures that a save action applies the udpated policy on top - // of the latest Package Config. So we just ignore the check against this value by - // forcing it to be the same as the value returned in the full agent config. - manifest_version: agentFullConfig.inputs[0].artifact_manifest.manifest_version, + // of the latest Package Policy. So we just ignore the check against this value by + // forcing it to be the same as the value returned in the full agent policy. + manifest_version: agentFullPolicy.inputs[0].artifact_manifest.manifest_version, schema_version: 'v1', }, policy: { @@ -179,7 +179,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { use_output: 'default', }, ], - id: policyInfo.agentConfig.id, + id: policyInfo.agentPolicy.id, outputs: { default: { hosts: ['http://localhost:9200'], @@ -197,14 +197,14 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { }); }); }); - describe('when on Ingest Configurations Edit Package Config page', async () => { + describe('when on Ingest Policy Edit Package Policy page', async () => { let policyInfo: PolicyTestResourceInfo; beforeEach(async () => { // Create a policy and navigate to Ingest app policyInfo = await policyTestResources.createPolicy(); - await pageObjects.ingestManagerCreatePackageConfig.navigateToAgentConfigEditPackageConfig( - policyInfo.agentConfig.id, - policyInfo.packageConfig.id + await pageObjects.ingestManagerCreatePackagePolicy.navigateToAgentPolicyEditPackagePolicy( + policyInfo.agentPolicy.id, + policyInfo.packagePolicy.id ); }); afterEach(async () => { @@ -227,12 +227,12 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { await pageObjects.policy.confirmAndSave(); await testSubjects.existOrFail('policyDetailsSuccessMessage'); - await pageObjects.ingestManagerCreatePackageConfig.ensureOnEditPageOrFail(); + await pageObjects.ingestManagerCreatePackagePolicy.ensureOnEditPageOrFail(); }); - it('should navigate back to Ingest Configuration Edit package page on click of cancel button', async () => { + it('should navigate back to Ingest Policy Edit package page on click of cancel button', async () => { await (await testSubjects.find('editLinkToPolicyDetails')).click(); await (await pageObjects.policy.findCancelButton()).click(); - await pageObjects.ingestManagerCreatePackageConfig.ensureOnEditPageOrFail(); + await pageObjects.ingestManagerCreatePackagePolicy.ensureOnEditPageOrFail(); }); }); }); diff --git a/x-pack/test/security_solution_endpoint/apps/endpoint/policy_list.ts b/x-pack/test/security_solution_endpoint/apps/endpoint/policy_list.ts index cf93ca1b689914..49a7a2155a7005 100644 --- a/x-pack/test/security_solution_endpoint/apps/endpoint/policy_list.ts +++ b/x-pack/test/security_solution_endpoint/apps/endpoint/policy_list.ts @@ -13,7 +13,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { 'endpoint', 'policy', 'endpointPageUtils', - 'ingestManagerCreatePackageConfig', + 'ingestManagerCreatePackagePolicy', ]); const testSubjects = getService('testSubjects'); const policyTestResources = getService('policyTestResources'); @@ -78,7 +78,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { 'Protect East Coastrev. 1', 'elastic', 'elastic', - `v${policyInfo.packageConfig.package?.version}`, + `v${policyInfo.packagePolicy.package?.version}`, '', ]); [policyRow[2], policyRow[4]].forEach((relativeDate) => { @@ -86,11 +86,11 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { }); }); - it('should show agent config action as a link', async () => { + it('should show agent policy action as a link', async () => { await (await pageObjects.policy.findFirstActionsButton()).click(); - const agentConfigLink = await testSubjects.find('agentConfigLink'); - expect(await agentConfigLink.getAttribute('href')).to.match( - new RegExp(`\/ingestManager#\/configs\/${policyInfo.agentConfig.id}$`) + const agentPolicyLink = await testSubjects.find('agentPolicyLink'); + expect(await agentPolicyLink.getAttribute('href')).to.match( + new RegExp(`\/ingestManager#\/policies\/${policyInfo.agentPolicy.id}$`) ); // Close action menu await (await pageObjects.policy.findFirstActionsButton()).click(); @@ -111,47 +111,47 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { await (await pageObjects.policy.findHeaderCreateNewButton()).click(); }); - it('should redirect to ingest management integrations add package config', async () => { - await pageObjects.ingestManagerCreatePackageConfig.ensureOnCreatePageOrFail(); + it('should redirect to ingest management integrations add package policy', async () => { + await pageObjects.ingestManagerCreatePackagePolicy.ensureOnCreatePageOrFail(); }); it('should redirect user back to Policy List if Cancel button is clicked', async () => { - await (await pageObjects.ingestManagerCreatePackageConfig.findCancelButton()).click(); + await (await pageObjects.ingestManagerCreatePackagePolicy.findCancelButton()).click(); await pageObjects.policy.ensureIsOnPolicyPage(); }); it('should redirect user back to Policy List if Back link is clicked', async () => { - await (await pageObjects.ingestManagerCreatePackageConfig.findBackLink()).click(); + await (await pageObjects.ingestManagerCreatePackagePolicy.findBackLink()).click(); await pageObjects.policy.ensureIsOnPolicyPage(); }); it('should display custom endpoint configuration message', async () => { - await pageObjects.ingestManagerCreatePackageConfig.selectAgentConfig(); - const endpointConfig = await pageObjects.policy.findPackageConfigEndpointCustomConfiguration(); + await pageObjects.ingestManagerCreatePackagePolicy.selectAgentPolicy(); + const endpointConfig = await pageObjects.policy.findPackagePolicyEndpointCustomConfiguration(); expect(endpointConfig).not.to.be(undefined); }); - it('should have empty value for package configuration name', async () => { - await pageObjects.ingestManagerCreatePackageConfig.selectAgentConfig(); - expect(await pageObjects.ingestManagerCreatePackageConfig.getPackageConfigName()).to.be(''); + it('should have empty value for package policy name', async () => { + await pageObjects.ingestManagerCreatePackagePolicy.selectAgentPolicy(); + expect(await pageObjects.ingestManagerCreatePackagePolicy.getPackagePolicyName()).to.be(''); }); it('should redirect user back to Policy List after a successful save', async () => { const newPolicyName = `endpoint policy ${Date.now()}`; - await pageObjects.ingestManagerCreatePackageConfig.selectAgentConfig(); - await pageObjects.ingestManagerCreatePackageConfig.setPackageConfigName(newPolicyName); - await (await pageObjects.ingestManagerCreatePackageConfig.findDSaveButton()).click(); - await pageObjects.ingestManagerCreatePackageConfig.waitForSaveSuccessNotification(); + await pageObjects.ingestManagerCreatePackagePolicy.selectAgentPolicy(); + await pageObjects.ingestManagerCreatePackagePolicy.setPackagePolicyName(newPolicyName); + await (await pageObjects.ingestManagerCreatePackagePolicy.findDSaveButton()).click(); + await pageObjects.ingestManagerCreatePackagePolicy.waitForSaveSuccessNotification(); await pageObjects.policy.ensureIsOnPolicyPage(); await policyTestResources.deletePolicyByName(newPolicyName); }); }); describe('and user clicks on page header create button', () => { - it('should direct users to the ingest management integrations add package config', async () => { + it('should direct users to the ingest management integrations add package policy', async () => { await pageObjects.policy.navigateToPolicyList(); await (await pageObjects.policy.findOnboardingStartButton()).click(); - await pageObjects.ingestManagerCreatePackageConfig.ensureOnCreatePageOrFail(); + await pageObjects.ingestManagerCreatePackagePolicy.ensureOnCreatePageOrFail(); }); }); }); diff --git a/x-pack/test/security_solution_endpoint/page_objects/index.ts b/x-pack/test/security_solution_endpoint/page_objects/index.ts index 05762ba887c6fb..39a9e7009c3859 100644 --- a/x-pack/test/security_solution_endpoint/page_objects/index.ts +++ b/x-pack/test/security_solution_endpoint/page_objects/index.ts @@ -9,7 +9,7 @@ import { EndpointPageProvider } from './endpoint_page'; import { EndpointPolicyPageProvider } from './policy_page'; import { TrustedAppsPageProvider } from './trusted_apps_page'; import { EndpointPageUtils } from './page_utils'; -import { IngestManagerCreatePackageConfig } from './ingest_manager_create_package_config_page'; +import { IngestManagerCreatePackagePolicy } from './ingest_manager_create_package_policy_page'; export const pageObjects = { ...xpackFunctionalPageObjects, @@ -17,5 +17,5 @@ export const pageObjects = { policy: EndpointPolicyPageProvider, trustedApps: TrustedAppsPageProvider, endpointPageUtils: EndpointPageUtils, - ingestManagerCreatePackageConfig: IngestManagerCreatePackageConfig, + ingestManagerCreatePackagePolicy: IngestManagerCreatePackagePolicy, }; diff --git a/x-pack/test/security_solution_endpoint/page_objects/ingest_manager_create_package_config_page.ts b/x-pack/test/security_solution_endpoint/page_objects/ingest_manager_create_package_policy_page.ts similarity index 56% rename from x-pack/test/security_solution_endpoint/page_objects/ingest_manager_create_package_config_page.ts rename to x-pack/test/security_solution_endpoint/page_objects/ingest_manager_create_package_policy_page.ts index dfdb528b7362cd..13b1f8c9d9842b 100644 --- a/x-pack/test/security_solution_endpoint/page_objects/ingest_manager_create_package_config_page.ts +++ b/x-pack/test/security_solution_endpoint/page_objects/ingest_manager_create_package_policy_page.ts @@ -6,7 +6,7 @@ import { FtrProviderContext } from '../ftr_provider_context'; -export function IngestManagerCreatePackageConfig({ +export function IngestManagerCreatePackagePolicy({ getService, getPageObjects, }: FtrProviderContext) { @@ -16,90 +16,90 @@ export function IngestManagerCreatePackageConfig({ return { /** - * Validates that the page shown is the Package Config Create Page + * Validates that the page shown is the Package Policy Create Page */ async ensureOnCreatePageOrFail() { - await testSubjects.existOrFail('createPackageConfig_header'); + await testSubjects.existOrFail('createPackagePolicy_header'); }, /** * Finds and returns the Cancel button on the sticky bottom bar */ async findCancelButton() { - return await testSubjects.find('createPackageConfigCancelButton'); + return await testSubjects.find('createPackagePolicyCancelButton'); }, /** * Finds and returns the Cancel back link at the top of the create page */ async findBackLink() { - return await testSubjects.find('createPackageConfig_cancelBackLink'); + return await testSubjects.find('createPackagePolicy_cancelBackLink'); }, /** * Finds and returns the save button on the sticky bottom bar */ async findDSaveButton() { - return await testSubjects.find('createPackageConfigSaveButton'); + return await testSubjects.find('createPackagePolicySaveButton'); }, /** - * Selects an agent configuration on the form + * Selects an agent policy on the form * @param name - * Visual name of the configuration. if one is not provided, the first agent - * configuration on the list will be chosen + * Visual name of the policy. if one is not provided, the first agent + * policy on the list will be chosen */ - async selectAgentConfig(name?: string) { + async selectAgentPolicy(name?: string) { // if we have a name, then find the button with that `title` set. if (name) { await ( - await find.byCssSelector(`[data-test-subj="agentConfigItem"][title="${name}"]`) + await find.byCssSelector(`[data-test-subj="agentPolicyItem"][title="${name}"]`) ).click(); } - // Else, just select the first agent configuration that is present + // Else, just select the first agent policy that is present else { - await (await testSubjects.find('agentConfigItem')).click(); + await (await testSubjects.find('agentPolicyItem')).click(); } }, /** - * Returns the package config name currently populated on the input field + * Returns the package Policy name currently populated on the input field */ - async getPackageConfigName() { - return testSubjects.getAttribute('packageConfigNameInput', 'value'); + async getPackagePolicyName() { + return testSubjects.getAttribute('packagePolicyNameInput', 'value'); }, /** - * Set the name of the package config on the input field + * Set the name of the package Policy on the input field * @param name */ - async setPackageConfigName(name: string) { + async setPackagePolicyName(name: string) { // Because of the bottom sticky bar, we need to scroll section 2 into view // so that `setValue()` enters the data on the input field. await testSubjects.scrollIntoView('dataCollectionSetupStep'); - await testSubjects.setValue('packageConfigNameInput', name); + await testSubjects.setValue('packagePolicyNameInput', name); }, /** * Waits for the save Notification toast to be visible */ async waitForSaveSuccessNotification() { - await testSubjects.existOrFail('packageConfigCreateSuccessToast'); + await testSubjects.existOrFail('packagePolicyCreateSuccessToast'); }, /** - * Validates that the page shown is the Package Config Edit Page + * Validates that the page shown is the Package Policy Edit Page */ async ensureOnEditPageOrFail() { - await testSubjects.existOrFail('editPackageConfig_header'); + await testSubjects.existOrFail('editPackagePolicy_header'); }, /** - * Navigates to the Ingest Agent configuration Edit Package Config page + * Navigates to the Ingest Agent configuration Edit Package Policy page */ - async navigateToAgentConfigEditPackageConfig(agentConfigId: string, packageConfigId: string) { + async navigateToAgentPolicyEditPackagePolicy(agentPolicyId: string, packagePolicyId: string) { await pageObjects.common.navigateToApp('ingestManager', { - hash: `/configs/${agentConfigId}/edit-integration/${packageConfigId}`, + hash: `/policies/${agentPolicyId}/edit-integration/${packagePolicyId}`, }); await this.ensureOnEditPageOrFail(); }, diff --git a/x-pack/test/security_solution_endpoint/page_objects/policy_page.ts b/x-pack/test/security_solution_endpoint/page_objects/policy_page.ts index 8ee42d40263818..9c1fa0c6e86b21 100644 --- a/x-pack/test/security_solution_endpoint/page_objects/policy_page.ts +++ b/x-pack/test/security_solution_endpoint/page_objects/policy_page.ts @@ -106,12 +106,12 @@ export function EndpointPolicyPageProvider({ getService, getPageObjects }: FtrPr }, /** - * Used when looking a the Ingest create/edit package config pages. Finds the endpoint + * Used when looking a the Ingest create/edit package policy pages. Finds the endpoint * custom configuaration component * @param onEditPage */ - async findPackageConfigEndpointCustomConfiguration(onEditPage: boolean = false) { - return await testSubjects.find(`endpointPackageConfig_${onEditPage ? 'edit' : 'create'}`); + async findPackagePolicyEndpointCustomConfiguration(onEditPage: boolean = false) { + return await testSubjects.find(`endpointPackagePolicy_${onEditPage ? 'edit' : 'create'}`); }, /** diff --git a/x-pack/test/security_solution_endpoint/services/endpoint_policy.ts b/x-pack/test/security_solution_endpoint/services/endpoint_policy.ts index df7d117e91dcbf..349aa0bc3a9ea7 100644 --- a/x-pack/test/security_solution_endpoint/services/endpoint_policy.ts +++ b/x-pack/test/security_solution_endpoint/services/endpoint_policy.ts @@ -5,25 +5,25 @@ */ import { FtrProviderContext } from '../ftr_provider_context'; import { - CreateAgentConfigRequest, - CreateAgentConfigResponse, - CreatePackageConfigRequest, - CreatePackageConfigResponse, - PACKAGE_CONFIG_SAVED_OBJECT_TYPE, - DeleteAgentConfigRequest, - DeletePackageConfigsRequest, - GetPackageConfigsResponse, - GetFullAgentConfigResponse, + CreateAgentPolicyRequest, + CreateAgentPolicyResponse, + CreatePackagePolicyRequest, + CreatePackagePolicyResponse, + PACKAGE_POLICY_SAVED_OBJECT_TYPE, + DeleteAgentPolicyRequest, + DeletePackagePoliciesRequest, + GetPackagePoliciesResponse, + GetFullAgentPolicyResponse, GetPackagesResponse, } from '../../../plugins/ingest_manager/common'; import { factory as policyConfigFactory } from '../../../plugins/security_solution/common/endpoint/models/policy_config'; import { Immutable } from '../../../plugins/security_solution/common/endpoint/types'; const INGEST_API_ROOT = '/api/ingest_manager'; -const INGEST_API_AGENT_CONFIGS = `${INGEST_API_ROOT}/agent_configs`; -const INGEST_API_AGENT_CONFIGS_DELETE = `${INGEST_API_AGENT_CONFIGS}/delete`; -const INGEST_API_PACKAGE_CONFIGS = `${INGEST_API_ROOT}/package_configs`; -const INGEST_API_PACKAGE_CONFIGS_DELETE = `${INGEST_API_PACKAGE_CONFIGS}/delete`; +const INGEST_API_AGENT_POLICIES = `${INGEST_API_ROOT}/agent_policies`; +const INGEST_API_AGENT_POLICIES_DELETE = `${INGEST_API_AGENT_POLICIES}/delete`; +const INGEST_API_PACKAGE_POLICIES = `${INGEST_API_ROOT}/package_policies`; +const INGEST_API_PACKAGE_POLICIES_DELETE = `${INGEST_API_PACKAGE_POLICIES}/delete`; const INGEST_API_EPM_PACKAGES = `${INGEST_API_ROOT}/epm/packages`; const SECURITY_PACKAGES_ROUTE = `${INGEST_API_EPM_PACKAGES}?category=security`; @@ -32,17 +32,17 @@ const SECURITY_PACKAGES_ROUTE = `${INGEST_API_EPM_PACKAGES}?category=security`; * Holds information about the test resources created to support an Endpoint Policy */ export interface PolicyTestResourceInfo { - /** The Ingest agent configuration created */ - agentConfig: Immutable; - /** The Ingest Package Config created and added to agent configuration. + /** The Ingest agent policy created */ + agentPolicy: Immutable; + /** The Ingest Package Policy created and added to agent policy. * This is where Endpoint Policy is stored. */ - packageConfig: Immutable; + packagePolicy: Immutable; /** * Information about the endpoint package */ packageInfo: Immutable; - /** will clean up (delete) the objects created (agent config + Package Config) */ + /** will clean up (delete) the objects created (Agent Policy + Package Policy) */ cleanup: () => Promise; } @@ -64,7 +64,7 @@ export function EndpointPolicyTestResourcesProvider({ getService }: FtrProviderC // EPM does not currently have an API to get the "lastest" information for a page given its name, // so we'll retrieve a list of packages for a category of Security, and will then find the // endpoint package info. in the list. The request is kicked off here, but handled below after - // agent config creation so that they can be executed concurrently + // Agent Policy creation so that they can be executed concurrently let apiRequest: Promise; return () => { @@ -107,57 +107,57 @@ export function EndpointPolicyTestResourcesProvider({ getService }: FtrProviderC return { /** - * Retrieves the full Agent configuration, which mirrors what the Elastic Agent would get + * Retrieves the full Agent policy, which mirrors what the Elastic Agent would get * once they checkin. */ - async getFullAgentConfig(agentConfigId: string): Promise { - let fullAgentConfig: GetFullAgentConfigResponse['item']; + async getFullAgentPolicy(agentPolicyId: string): Promise { + let fullAgentPolicy: GetFullAgentPolicyResponse['item']; try { - const apiResponse: { body: GetFullAgentConfigResponse } = await supertest - .get(`${INGEST_API_AGENT_CONFIGS}/${agentConfigId}/full`) + const apiResponse: { body: GetFullAgentPolicyResponse } = await supertest + .get(`${INGEST_API_AGENT_POLICIES}/${agentPolicyId}/full`) .expect(200); - fullAgentConfig = apiResponse.body.item; + fullAgentPolicy = apiResponse.body.item; } catch (error) { - return logSupertestApiErrorAndThrow('Unable to get full Agent Configuration', error); + return logSupertestApiErrorAndThrow('Unable to get full Agent policy', error); } - return fullAgentConfig!; + return fullAgentPolicy!; }, /** - * Creates an Ingest Agent Configuration and adds to it the Endpoint Package Config that + * Creates an Ingest Agent policy and adds to it the Endpoint Package Policy that * stores the Policy configuration data */ async createPolicy(): Promise { - // create agent config - let agentConfig: CreateAgentConfigResponse['item']; + // create Agent Policy + let agentPolicy: CreateAgentPolicyResponse['item']; try { - const newAgentconfigData: CreateAgentConfigRequest['body'] = { + const newAgentPolicyData: CreateAgentPolicyRequest['body'] = { name: 'East Coast', description: 'East Coast call center', namespace: 'default', }; - const { body: createResponse }: { body: CreateAgentConfigResponse } = await supertest - .post(INGEST_API_AGENT_CONFIGS) + const { body: createResponse }: { body: CreateAgentPolicyResponse } = await supertest + .post(INGEST_API_AGENT_POLICIES) .set('kbn-xsrf', 'xxx') - .send(newAgentconfigData) + .send(newAgentPolicyData) .expect(200); - agentConfig = createResponse.item; + agentPolicy = createResponse.item; } catch (error) { - return logSupertestApiErrorAndThrow(`Unable to create Agent Config via Ingest!`, error); + return logSupertestApiErrorAndThrow(`Unable to create Agent Policy via Ingest!`, error); } // Retrieve the Endpoint package information const endpointPackageInfo = await retrieveEndpointPackageInfo(); - // create Package Config and associated it to agent config - let packageConfig: CreatePackageConfigResponse['item']; + // create Package Policy and associated it to Agent Policy + let packagePolicy: CreatePackagePolicyResponse['item']; try { - const newPackageConfigData: CreatePackageConfigRequest['body'] = { + const newPackagePolicyData: CreatePackagePolicyRequest['body'] = { name: 'Protect East Coast', description: 'Protect the worlds data - but in the East Coast', - config_id: agentConfig!.id, + policy_id: agentPolicy!.id, enabled: true, output_id: '', inputs: [ @@ -181,94 +181,94 @@ export function EndpointPolicyTestResourcesProvider({ getService }: FtrProviderC }; const { body: createResponse, - }: { body: CreatePackageConfigResponse } = await supertest - .post(INGEST_API_PACKAGE_CONFIGS) + }: { body: CreatePackagePolicyResponse } = await supertest + .post(INGEST_API_PACKAGE_POLICIES) .set('kbn-xsrf', 'xxx') - .send(newPackageConfigData) + .send(newPackagePolicyData) .expect(200); - packageConfig = createResponse.item; + packagePolicy = createResponse.item; } catch (error) { - return logSupertestApiErrorAndThrow(`Unable to create Package Config via Ingest!`, error); + return logSupertestApiErrorAndThrow(`Unable to create Package Policy via Ingest!`, error); } return { - agentConfig, - packageConfig, + agentPolicy, + packagePolicy, packageInfo: endpointPackageInfo!, async cleanup() { - // Delete Package Config + // Delete Package Policy try { - const deletePackageConfigData: DeletePackageConfigsRequest['body'] = { - packageConfigIds: [packageConfig.id], + const deletePackagePolicyData: DeletePackagePoliciesRequest['body'] = { + packagePolicyIds: [packagePolicy.id], }; await supertest - .post(INGEST_API_PACKAGE_CONFIGS_DELETE) + .post(INGEST_API_PACKAGE_POLICIES_DELETE) .set('kbn-xsrf', 'xxx') - .send(deletePackageConfigData) + .send(deletePackagePolicyData) .expect(200); } catch (error) { - logSupertestApiErrorAndThrow('Unable to delete Package Config via Ingest!', error); + logSupertestApiErrorAndThrow('Unable to delete Package Policy via Ingest!', error); } - // Delete Agent config + // Delete Agent Policy try { - const deleteAgentConfigData: DeleteAgentConfigRequest['body'] = { - agentConfigId: agentConfig.id, + const deleteAgentPolicyData: DeleteAgentPolicyRequest['body'] = { + agentPolicyId: agentPolicy.id, }; await supertest - .post(INGEST_API_AGENT_CONFIGS_DELETE) + .post(INGEST_API_AGENT_POLICIES_DELETE) .set('kbn-xsrf', 'xxx') - .send(deleteAgentConfigData) + .send(deleteAgentPolicyData) .expect(200); } catch (error) { - logSupertestApiErrorAndThrow('Unable to delete Agent Config via Ingest!', error); + logSupertestApiErrorAndThrow('Unable to delete Agent Policy via Ingest!', error); } }, }; }, /** - * Deletes a policy (Package Config) by using the policy name + * Deletes a policy (Package Policy) by using the policy name * @param name */ async deletePolicyByName(name: string) { - let packageConfigList: GetPackageConfigsResponse['items']; + let packagePolicyList: GetPackagePoliciesResponse['items']; try { const { - body: packageConfigsResponse, - }: { body: GetPackageConfigsResponse } = await supertest - .get(INGEST_API_PACKAGE_CONFIGS) + body: packagePoliciesResponse, + }: { body: GetPackagePoliciesResponse } = await supertest + .get(INGEST_API_PACKAGE_POLICIES) .set('kbn-xsrf', 'xxx') - .query({ kuery: `${PACKAGE_CONFIG_SAVED_OBJECT_TYPE}.name: ${name}` }) + .query({ kuery: `${PACKAGE_POLICY_SAVED_OBJECT_TYPE}.name: ${name}` }) .send() .expect(200); - packageConfigList = packageConfigsResponse.items; + packagePolicyList = packagePoliciesResponse.items; } catch (error) { return logSupertestApiErrorAndThrow( - `Unable to get list of Package Configs with name=${name}`, + `Unable to get list of Package Policies with name=${name}`, error ); } - if (packageConfigList.length === 0) { + if (packagePolicyList.length === 0) { throw new Error(`Policy named '${name}' was not found!`); } - if (packageConfigList.length > 1) { - throw new Error(`Found ${packageConfigList.length} Policies - was expecting only one!`); + if (packagePolicyList.length > 1) { + throw new Error(`Found ${packagePolicyList.length} Policies - was expecting only one!`); } try { - const deletePackageConfigData: DeletePackageConfigsRequest['body'] = { - packageConfigIds: [packageConfigList[0].id], + const deletePackagePolicyData: DeletePackagePoliciesRequest['body'] = { + packagePolicyIds: [packagePolicyList[0].id], }; await supertest - .post(INGEST_API_PACKAGE_CONFIGS_DELETE) + .post(INGEST_API_PACKAGE_POLICIES_DELETE) .set('kbn-xsrf', 'xxx') - .send(deletePackageConfigData) + .send(deletePackagePolicyData) .expect(200); } catch (error) { - logSupertestApiErrorAndThrow('Unable to delete Package Config via Ingest!', error); + logSupertestApiErrorAndThrow('Unable to delete Package Policy via Ingest!', error); } }, };