LogstashUI 0.5.5.dev0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (762) hide show
  1. AI/__init__.py +0 -0
  2. AI/integration_factory.py +1392 -0
  3. AI/migrations/0001_initial.py +58 -0
  4. AI/migrations/0002_draftdefinition_normalizers.py +23 -0
  5. AI/migrations/0003_delete_aisettings_delete_draftdefinition.py +19 -0
  6. AI/migrations/__init__.py +0 -0
  7. AI/models.py +5 -0
  8. AI/static/js/integration_factory.js +1102 -0
  9. AI/system_prompts/dashboard_generator.md +367 -0
  10. AI/system_prompts/grok_patterns.txt +95 -0
  11. AI/system_prompts/ingest_pipeline_generator.md +331 -0
  12. AI/system_prompts/ingest_pipeline_processors.json +2851 -0
  13. AI/system_prompts/ingest_verifier.md +84 -0
  14. AI/system_prompts/integrations_list.json +2690 -0
  15. AI/system_prompts/log_classifier.md +134 -0
  16. AI/system_prompts/template_creator.md +123 -0
  17. AI/templates/integration_factory.html +200 -0
  18. AI/urls.py +16 -0
  19. AI/views.py +20 -0
  20. API/__init__.py +0 -0
  21. API/admin.py +7 -0
  22. API/api.http +784 -0
  23. API/apps.py +9 -0
  24. API/auth.py +101 -0
  25. API/connections_views.py +312 -0
  26. API/guides.py +88 -0
  27. API/mcp/__init__.py +5 -0
  28. API/mcp/dispatch.py +179 -0
  29. API/mcp/tools.py +890 -0
  30. API/mcp/views.py +215 -0
  31. API/migrations/__init__.py +0 -0
  32. API/models.py +7 -0
  33. API/pipelines_views.py +1224 -0
  34. API/policies_views.py +1015 -0
  35. API/security_views.py +488 -0
  36. API/simulation_detail.py +219 -0
  37. API/snmp_views.py +1539 -0
  38. API/urls.py +81 -0
  39. Common/__init__.py +0 -0
  40. Common/ai/agent_builder.py +690 -0
  41. Common/context_processors.py +49 -0
  42. Common/decorators.py +68 -0
  43. Common/elastic_utils.py +1154 -0
  44. Common/encryption.py +271 -0
  45. Common/error_handlers.py +65 -0
  46. Common/formatters.py +106 -0
  47. Common/logstash_config_parse.py +1469 -0
  48. Common/logstash_utils.py +34 -0
  49. Common/middleware.py +216 -0
  50. Common/product_ca.py +1124 -0
  51. Common/validators.py +66 -0
  52. Documentation/__init__.py +0 -0
  53. Documentation/admin.py +7 -0
  54. Documentation/apps.py +9 -0
  55. Documentation/content/CHANGELOG.md +890 -0
  56. Documentation/content/docs/getting_started.md +92 -0
  57. Documentation/content/docs/index.md +124 -0
  58. Documentation/content/docs/logstashagent/configuration/index.md +60 -0
  59. Documentation/content/docs/logstashagent/configuration/logstashagent.yml.md +141 -0
  60. Documentation/content/docs/logstashagent/general/build.md +217 -0
  61. Documentation/content/docs/logstashagent/general/index.md +38 -0
  62. Documentation/content/docs/logstashagent/general/roles.md +267 -0
  63. Documentation/content/docs/logstashagent/index.md +264 -0
  64. Documentation/content/docs/logstashui/SNMP/Quickstart.md +94 -0
  65. Documentation/content/docs/logstashui/SNMP/architecture.md +64 -0
  66. Documentation/content/docs/logstashui/SNMP/configuration.md +147 -0
  67. Documentation/content/docs/logstashui/SNMP/data_overview.md +59 -0
  68. Documentation/content/docs/logstashui/SNMP/deploying_changes.md +71 -0
  69. Documentation/content/docs/logstashui/SNMP/device_support.md +39 -0
  70. Documentation/content/docs/logstashui/SNMP/discovery.md +48 -0
  71. Documentation/content/docs/logstashui/SNMP/index.md +58 -0
  72. Documentation/content/docs/logstashui/SNMP/pipeline_generation.md +63 -0
  73. Documentation/content/docs/logstashui/SNMP/schema.md +595 -0
  74. Documentation/content/docs/logstashui/SNMP/testing.md +47 -0
  75. Documentation/content/docs/logstashui/SNMP/traps.md +45 -0
  76. Documentation/content/docs/logstashui/SNMP/tsds_implementation.md +82 -0
  77. Documentation/content/docs/logstashui/agent_guides/concepts.md +25 -0
  78. Documentation/content/docs/logstashui/agent_guides/deploy.md +30 -0
  79. Documentation/content/docs/logstashui/agent_guides/pipeline-review.md +24 -0
  80. Documentation/content/docs/logstashui/agent_guides/simulation.md +55 -0
  81. Documentation/content/docs/logstashui/agent_guides/snmp.md +57 -0
  82. Documentation/content/docs/logstashui/agent_guides/troubleshooting.md +21 -0
  83. Documentation/content/docs/logstashui/architecture.md +11 -0
  84. Documentation/content/docs/logstashui/compatibility.md +58 -0
  85. Documentation/content/docs/logstashui/configuration/environment.md +193 -0
  86. Documentation/content/docs/logstashui/configuration/host_mode.md +94 -0
  87. Documentation/content/docs/logstashui/configuration/index.md +72 -0
  88. Documentation/content/docs/logstashui/configuration/logstash_proxy.md +138 -0
  89. Documentation/content/docs/logstashui/configuration/logstashui.yml.md +16 -0
  90. Documentation/content/docs/logstashui/configuration/simulation.md +84 -0
  91. Documentation/content/docs/logstashui/database/examples/README.md +15 -0
  92. Documentation/content/docs/logstashui/database/examples/create-mariadb.sql +13 -0
  93. Documentation/content/docs/logstashui/database/examples/create-mysql.sql +12 -0
  94. Documentation/content/docs/logstashui/database/examples/create-postgresql.sql +13 -0
  95. Documentation/content/docs/logstashui/database/examples/schema-mysql.sql +502 -0
  96. Documentation/content/docs/logstashui/database/examples/schema-postgresql.sql +1709 -0
  97. Documentation/content/docs/logstashui/database/index.md +79 -0
  98. Documentation/content/docs/logstashui/database/migration.md +75 -0
  99. Documentation/content/docs/logstashui/general/build.md +154 -0
  100. Documentation/content/docs/logstashui/general/deploy.md +122 -0
  101. Documentation/content/docs/logstashui/general/deployment-recs.md +32 -0
  102. Documentation/content/docs/logstashui/general/index.md +62 -0
  103. Documentation/content/docs/logstashui/general/offline.md +68 -0
  104. Documentation/content/docs/logstashui/general/updating.md +50 -0
  105. Documentation/content/docs/logstashui/index.md +90 -0
  106. Documentation/content/docs/logstashui/kubernetes/cnpg.md +98 -0
  107. Documentation/content/docs/logstashui/kubernetes/envoy-gateway.md +112 -0
  108. Documentation/content/docs/logstashui/kubernetes/examples/README.md +46 -0
  109. Documentation/content/docs/logstashui/kubernetes/examples/embedded-agent.yaml +122 -0
  110. Documentation/content/docs/logstashui/kubernetes/examples/mysql/configmap.yaml +41 -0
  111. Documentation/content/docs/logstashui/kubernetes/examples/mysql/ingress.yaml +31 -0
  112. Documentation/content/docs/logstashui/kubernetes/examples/mysql/namespace.yaml +8 -0
  113. Documentation/content/docs/logstashui/kubernetes/examples/mysql/secret.yaml +19 -0
  114. Documentation/content/docs/logstashui/kubernetes/examples/mysql/statefulset.yaml +106 -0
  115. Documentation/content/docs/logstashui/kubernetes/examples/postgresql/cnpg.yaml +25 -0
  116. Documentation/content/docs/logstashui/kubernetes/examples/postgresql/configmap.yaml +42 -0
  117. Documentation/content/docs/logstashui/kubernetes/examples/postgresql/ingress.yaml +31 -0
  118. Documentation/content/docs/logstashui/kubernetes/examples/postgresql/namespace.yaml +8 -0
  119. Documentation/content/docs/logstashui/kubernetes/examples/postgresql/secret.yaml +19 -0
  120. Documentation/content/docs/logstashui/kubernetes/examples/postgresql/statefulset.yaml +106 -0
  121. Documentation/content/docs/logstashui/kubernetes/examples/sqlite/configmap.yaml +35 -0
  122. Documentation/content/docs/logstashui/kubernetes/examples/sqlite/ingress.yaml +31 -0
  123. Documentation/content/docs/logstashui/kubernetes/examples/sqlite/namespace.yaml +8 -0
  124. Documentation/content/docs/logstashui/kubernetes/examples/sqlite/secret.yaml +18 -0
  125. Documentation/content/docs/logstashui/kubernetes/examples/sqlite/statefulset.yaml +106 -0
  126. Documentation/content/docs/logstashui/kubernetes/index.md +121 -0
  127. Documentation/content/docs/logstashui/mcp.md +224 -0
  128. Documentation/content/docs/logstashui/mcp_scenarios.md +234 -0
  129. Documentation/content/docs/logstashui/rest_api.md +2783 -0
  130. Documentation/content/docs/logstashui/utilities/dissect_debugger.md +89 -0
  131. Documentation/content/docs/logstashui/utilities/grok_debugger.md +114 -0
  132. Documentation/content/docs/logstashui/utilities/index.md +40 -0
  133. Documentation/content/images/LogstashIcon.png +0 -0
  134. Documentation/content/images/architecture.png +0 -0
  135. Documentation/content/images/connection_manager.png +0 -0
  136. Documentation/content/images/control_plane.png +0 -0
  137. Documentation/content/images/graph.gif +0 -0
  138. Documentation/content/images/login.png +0 -0
  139. Documentation/content/images/monitoring.png +0 -0
  140. Documentation/content/images/new_connection.gif +0 -0
  141. Documentation/content/images/simulate.gif +0 -0
  142. Documentation/content/images/simulate.png +0 -0
  143. Documentation/content/images/snmp.gif +0 -0
  144. Documentation/content/images/snmp.png +0 -0
  145. Documentation/content/images/snmp_architecture.png +0 -0
  146. Documentation/migrations/__init__.py +0 -0
  147. Documentation/models.py +9 -0
  148. Documentation/static/css/markdown.css +250 -0
  149. Documentation/templates/documentation.html +225 -0
  150. Documentation/templates/nav_item.html +41 -0
  151. Documentation/urls.py +11 -0
  152. Documentation/views.py +442 -0
  153. LogstashUI/__init__.py +0 -0
  154. LogstashUI/__main__.py +10 -0
  155. LogstashUI/asgi.py +16 -0
  156. LogstashUI/cli.py +626 -0
  157. LogstashUI/config.py +116 -0
  158. LogstashUI/database.py +263 -0
  159. LogstashUI/insecure_http.py +117 -0
  160. LogstashUI/logging_config.py +99 -0
  161. LogstashUI/migrate_engine.py +282 -0
  162. LogstashUI/packaging/__init__.py +3 -0
  163. LogstashUI/packaging/logstashui.default +68 -0
  164. LogstashUI/packaging/logstashui.service.in +22 -0
  165. LogstashUI/paths.py +181 -0
  166. LogstashUI/settings.py +437 -0
  167. LogstashUI/telemetry.py +159 -0
  168. LogstashUI/urls.py +56 -0
  169. LogstashUI/wsgi.py +77 -0
  170. Management/__init__.py +0 -0
  171. Management/apps.py +10 -0
  172. Management/migrations/0001_initial.py +29 -0
  173. Management/migrations/0002_settings.py +25 -0
  174. Management/migrations/0003_settings_agent_ui_url.py +29 -0
  175. Management/migrations/0004_settings_logstash_artifact_base_url.py +29 -0
  176. Management/migrations/__init__.py +0 -0
  177. Management/models.py +92 -0
  178. Management/templates/api_tokens.html +214 -0
  179. Management/templates/components/api_token_created.html +38 -0
  180. Management/templates/components/api_token_row.html +84 -0
  181. Management/templates/components/logstash_artifact_row.html +100 -0
  182. Management/templates/components/logstash_artifact_tbody.html +26 -0
  183. Management/templates/components/user_row.html +67 -0
  184. Management/templates/logs.html +98 -0
  185. Management/templates/logstash_artifacts.html +172 -0
  186. Management/templates/management.html +80 -0
  187. Management/templates/management_settings.html +320 -0
  188. Management/templates/registration/login.html +404 -0
  189. Management/templates/users.html +304 -0
  190. Management/urls.py +23 -0
  191. Management/views.py +804 -0
  192. Monitoring/__init__.py +0 -0
  193. Monitoring/apps.py +9 -0
  194. Monitoring/migrations/__init__.py +0 -0
  195. Monitoring/static/js/monitoring.js +463 -0
  196. Monitoring/templates/components/node_metrics.html +161 -0
  197. Monitoring/templates/components/pipeline_metrics.html +189 -0
  198. Monitoring/templates/monitoring.html +271 -0
  199. Monitoring/urls.py +16 -0
  200. Monitoring/views.py +724 -0
  201. PipelineManager/__init__.py +0 -0
  202. PipelineManager/agent_api.py +1173 -0
  203. PipelineManager/agent_client.py +59 -0
  204. PipelineManager/agent_modes.py +880 -0
  205. PipelineManager/agent_policies.py +689 -0
  206. PipelineManager/agent_versions.py +151 -0
  207. PipelineManager/apps.py +10 -0
  208. PipelineManager/artifact_metrics.py +171 -0
  209. PipelineManager/artifacts.py +820 -0
  210. PipelineManager/connections_crud.py +722 -0
  211. PipelineManager/data/default_jvm.options +76 -0
  212. PipelineManager/data/default_log4j2.properties +165 -0
  213. PipelineManager/data/default_logstash.yml +405 -0
  214. PipelineManager/data/plugins.json +29109 -0
  215. PipelineManager/editor_views.py +608 -0
  216. PipelineManager/forms.py +284 -0
  217. PipelineManager/manager_views.py +490 -0
  218. PipelineManager/migrations/0001_initial.py +38 -0
  219. PipelineManager/migrations/0002_alter_connection_connection_type_and_more.py +38 -0
  220. PipelineManager/migrations/0003_policy_connection_policy.py +38 -0
  221. PipelineManager/migrations/0004_policy_current_revision_number_and_more.py +75 -0
  222. PipelineManager/migrations/0005_apikey_enrollmenttoken.py +38 -0
  223. PipelineManager/migrations/0006_enrollmenttoken_name.py +18 -0
  224. PipelineManager/migrations/0007_alter_enrollmenttoken_options_and_more.py +21 -0
  225. PipelineManager/migrations/0008_connection_agent_id.py +18 -0
  226. PipelineManager/migrations/0009_connection_last_check_in_policy_jvm_options_hash_and_more.py +33 -0
  227. PipelineManager/migrations/0010_keystore_revision_number_pipeline_revision_number.py +23 -0
  228. PipelineManager/migrations/0011_keystore_kv_hash.py +18 -0
  229. PipelineManager/migrations/0012_policy_binary_path.py +18 -0
  230. PipelineManager/migrations/0013_connection_status_blob.py +18 -0
  231. PipelineManager/migrations/0014_pipeline_pipeline_batch_delay_and_more.py +43 -0
  232. PipelineManager/migrations/0015_add_pipeline_hash.py +18 -0
  233. PipelineManager/migrations/0016_backfill_pipeline_hash.py +32 -0
  234. PipelineManager/migrations/0017_policy_keystore_password.py +31 -0
  235. PipelineManager/migrations/0018_policy_last_deployed_at.py +18 -0
  236. PipelineManager/migrations/0019_connection_restart_on_next_checkin.py +18 -0
  237. PipelineManager/migrations/0020_pipeline_no_input_pipeline_non_reloadable.py +23 -0
  238. PipelineManager/migrations/0021_connection_desired_agent_version.py +18 -0
  239. PipelineManager/migrations/0022_keystore_managed_by_pipeline_managed_by.py +23 -0
  240. PipelineManager/migrations/0023_agent_modes_policy_connection.py +89 -0
  241. PipelineManager/migrations/0024_seed_system_policies.py +173 -0
  242. PipelineManager/migrations/0025_packaged_managed_policy_types.py +166 -0
  243. PipelineManager/migrations/0026_normalize_opt_logstash_agent_paths.py +63 -0
  244. PipelineManager/migrations/0027_packaged_managed_default_ports.py +49 -0
  245. PipelineManager/migrations/0028_apikey_admin_tokens.py +80 -0
  246. PipelineManager/migrations/0029_logstash_artifacts.py +45 -0
  247. PipelineManager/migrations/0030_connection_allow_self_signed_certs.py +33 -0
  248. PipelineManager/migrations/0031_deploy_system_policies.py +93 -0
  249. PipelineManager/migrations/0032_connection_agent_inbound_key.py +30 -0
  250. PipelineManager/migrations/0033_simulation_result.py +26 -0
  251. PipelineManager/migrations/__init__.py +0 -0
  252. PipelineManager/models.py +1300 -0
  253. PipelineManager/pipelines_crud.py +738 -0
  254. PipelineManager/policies_crud.py +772 -0
  255. PipelineManager/sim_keystore.py +319 -0
  256. PipelineManager/simulation.py +1581 -0
  257. PipelineManager/static/css/codemirror.min.css +1 -0
  258. PipelineManager/static/css/graph_move.css +79 -0
  259. PipelineManager/static/css/monokai.min.css +1 -0
  260. PipelineManager/static/css/move_mode.css +144 -0
  261. PipelineManager/static/css/show-hint.min.css +1 -0
  262. PipelineManager/static/images/age.png +0 -0
  263. PipelineManager/static/images/aggregate.png +0 -0
  264. PipelineManager/static/images/alter.png +0 -0
  265. PipelineManager/static/images/azure_event_hubs.png +0 -0
  266. PipelineManager/static/images/beats.png +0 -0
  267. PipelineManager/static/images/boundary.png +0 -0
  268. PipelineManager/static/images/bytes.png +0 -0
  269. PipelineManager/static/images/cidr.png +0 -0
  270. PipelineManager/static/images/cipher.png +0 -0
  271. PipelineManager/static/images/circonus.png +0 -0
  272. PipelineManager/static/images/clone.png +0 -0
  273. PipelineManager/static/images/cloudwatch.png +0 -0
  274. PipelineManager/static/images/comment.png +0 -0
  275. PipelineManager/static/images/continue.png +0 -0
  276. PipelineManager/static/images/couchdb_changes.png +0 -0
  277. PipelineManager/static/images/csv.png +0 -0
  278. PipelineManager/static/images/datadog.png +0 -0
  279. PipelineManager/static/images/datadog_metrics.png +0 -0
  280. PipelineManager/static/images/date.png +0 -0
  281. PipelineManager/static/images/de_dot.png +0 -0
  282. PipelineManager/static/images/dead_letter_queue.png +0 -0
  283. PipelineManager/static/images/dissect.png +0 -0
  284. PipelineManager/static/images/dns.png +0 -0
  285. PipelineManager/static/images/drop.png +0 -0
  286. PipelineManager/static/images/dynatrace.png +0 -0
  287. PipelineManager/static/images/elapsed.png +0 -0
  288. PipelineManager/static/images/elastic_agent.png +0 -0
  289. PipelineManager/static/images/elastic_integration.png +0 -0
  290. PipelineManager/static/images/elastic_serverless_forwarder.png +0 -0
  291. PipelineManager/static/images/elastic_workplace_search.png +0 -0
  292. PipelineManager/static/images/elasticsearch.png +0 -0
  293. PipelineManager/static/images/else.png +0 -0
  294. PipelineManager/static/images/else_if.png +0 -0
  295. PipelineManager/static/images/email.png +0 -0
  296. PipelineManager/static/images/environment.png +0 -0
  297. PipelineManager/static/images/exec.png +0 -0
  298. PipelineManager/static/images/extractnumbers.png +0 -0
  299. PipelineManager/static/images/file.png +0 -0
  300. PipelineManager/static/images/fingerprint.png +0 -0
  301. PipelineManager/static/images/ganglia.png +0 -0
  302. PipelineManager/static/images/gelf.png +0 -0
  303. PipelineManager/static/images/generator.png +0 -0
  304. PipelineManager/static/images/geoip.png +0 -0
  305. PipelineManager/static/images/github.png +0 -0
  306. PipelineManager/static/images/google_bigquery.png +0 -0
  307. PipelineManager/static/images/google_cloud_storage.png +0 -0
  308. PipelineManager/static/images/google_pubsub.png +0 -0
  309. PipelineManager/static/images/graphite.png +0 -0
  310. PipelineManager/static/images/graphtastic.png +0 -0
  311. PipelineManager/static/images/grok.png +0 -0
  312. PipelineManager/static/images/heartbeat.png +0 -0
  313. PipelineManager/static/images/http.png +0 -0
  314. PipelineManager/static/images/http_poller.png +0 -0
  315. PipelineManager/static/images/i18n.png +0 -0
  316. PipelineManager/static/images/if.png +0 -0
  317. PipelineManager/static/images/imap.png +0 -0
  318. PipelineManager/static/images/influxdb.png +0 -0
  319. PipelineManager/static/images/irc.png +0 -0
  320. PipelineManager/static/images/java_generator.png +0 -0
  321. PipelineManager/static/images/java_stdin.png +0 -0
  322. PipelineManager/static/images/java_stdout.png +0 -0
  323. PipelineManager/static/images/java_uuid.png +0 -0
  324. PipelineManager/static/images/jdbc.png +0 -0
  325. PipelineManager/static/images/jdbc_static.png +0 -0
  326. PipelineManager/static/images/jdbc_streaming.png +0 -0
  327. PipelineManager/static/images/jms.png +0 -0
  328. PipelineManager/static/images/jmx.png +0 -0
  329. PipelineManager/static/images/json.png +0 -0
  330. PipelineManager/static/images/json_encode.png +0 -0
  331. PipelineManager/static/images/juggernaut.png +0 -0
  332. PipelineManager/static/images/kafka.png +0 -0
  333. PipelineManager/static/images/kinesis.png +0 -0
  334. PipelineManager/static/images/kv.png +0 -0
  335. PipelineManager/static/images/librato.png +0 -0
  336. PipelineManager/static/images/log4j.png +0 -0
  337. PipelineManager/static/images/loggly.png +0 -0
  338. PipelineManager/static/images/logstash.png +0 -0
  339. PipelineManager/static/images/lumberjack.png +0 -0
  340. PipelineManager/static/images/meetup.png +0 -0
  341. PipelineManager/static/images/memcached.png +0 -0
  342. PipelineManager/static/images/metriccatcher.png +0 -0
  343. PipelineManager/static/images/metricize.png +0 -0
  344. PipelineManager/static/images/metrics.png +0 -0
  345. PipelineManager/static/images/mongodb.png +0 -0
  346. PipelineManager/static/images/mutate.png +0 -0
  347. PipelineManager/static/images/nagios.png +0 -0
  348. PipelineManager/static/images/nagios_nsca.png +0 -0
  349. PipelineManager/static/images/opentsdb.png +0 -0
  350. PipelineManager/static/images/pagerduty.png +0 -0
  351. PipelineManager/static/images/pipe.png +0 -0
  352. PipelineManager/static/images/pipeline.png +0 -0
  353. PipelineManager/static/images/prune.png +0 -0
  354. PipelineManager/static/images/puppet_facter.png +0 -0
  355. PipelineManager/static/images/rabbitmq.png +0 -0
  356. PipelineManager/static/images/range.png +0 -0
  357. PipelineManager/static/images/redis.png +0 -0
  358. PipelineManager/static/images/redmine.png +0 -0
  359. PipelineManager/static/images/relp.png +0 -0
  360. PipelineManager/static/images/riak.png +0 -0
  361. PipelineManager/static/images/riemann.png +0 -0
  362. PipelineManager/static/images/rss.png +0 -0
  363. PipelineManager/static/images/ruby.png +0 -0
  364. PipelineManager/static/images/s3-sns-sqs.png +0 -0
  365. PipelineManager/static/images/s3.png +0 -0
  366. PipelineManager/static/images/salesforce.png +0 -0
  367. PipelineManager/static/images/sink.png +0 -0
  368. PipelineManager/static/images/sleep.png +0 -0
  369. PipelineManager/static/images/snmp.png +0 -0
  370. PipelineManager/static/images/snmptrap.png +0 -0
  371. PipelineManager/static/images/sns.png +0 -0
  372. PipelineManager/static/images/solr_http.png +0 -0
  373. PipelineManager/static/images/split.png +0 -0
  374. PipelineManager/static/images/sqlite.png +0 -0
  375. PipelineManager/static/images/sqs.png +0 -0
  376. PipelineManager/static/images/statsd.png +0 -0
  377. PipelineManager/static/images/stdin.png +0 -0
  378. PipelineManager/static/images/stdout.png +0 -0
  379. PipelineManager/static/images/stomp.png +0 -0
  380. PipelineManager/static/images/syslog.png +0 -0
  381. PipelineManager/static/images/syslog_pri.png +0 -0
  382. PipelineManager/static/images/tcp.png +0 -0
  383. PipelineManager/static/images/threats_classifier.png +0 -0
  384. PipelineManager/static/images/throttle.png +0 -0
  385. PipelineManager/static/images/timber.png +0 -0
  386. PipelineManager/static/images/tld.png +0 -0
  387. PipelineManager/static/images/translate.png +0 -0
  388. PipelineManager/static/images/truncate.png +0 -0
  389. PipelineManager/static/images/twitter.png +0 -0
  390. PipelineManager/static/images/udp.png +0 -0
  391. PipelineManager/static/images/unix.png +0 -0
  392. PipelineManager/static/images/urldecode.png +0 -0
  393. PipelineManager/static/images/useragent.png +0 -0
  394. PipelineManager/static/images/uuid.png +0 -0
  395. PipelineManager/static/images/varnishlog.png +0 -0
  396. PipelineManager/static/images/webhdfs.png +0 -0
  397. PipelineManager/static/images/websocket.png +0 -0
  398. PipelineManager/static/images/wmi.png +0 -0
  399. PipelineManager/static/images/wurfl_device_detection.png +0 -0
  400. PipelineManager/static/images/xml.png +0 -0
  401. PipelineManager/static/images/xmpp.png +0 -0
  402. PipelineManager/static/images/zabbix.png +0 -0
  403. PipelineManager/static/js/agent_inspect_modal.js +141 -0
  404. PipelineManager/static/js/agent_policies.js +3746 -0
  405. PipelineManager/static/js/agent_status_sse.js +166 -0
  406. PipelineManager/static/js/codemirror.min.js +1 -0
  407. PipelineManager/static/js/connections_table.js +551 -0
  408. PipelineManager/static/js/d3.v7.js +20625 -0
  409. PipelineManager/static/js/diff_modal.js +995 -0
  410. PipelineManager/static/js/expression_editor.js +291 -0
  411. PipelineManager/static/js/js-yaml.min.js +1 -0
  412. PipelineManager/static/js/logstashyml_guides.js +1063 -0
  413. PipelineManager/static/js/move_graph.js +577 -0
  414. PipelineManager/static/js/move_mode.js +559 -0
  415. PipelineManager/static/js/pipeline_editor.js +4102 -0
  416. PipelineManager/static/js/pipeline_graph_editor.js +3542 -0
  417. PipelineManager/static/js/pipeline_list.js +274 -0
  418. PipelineManager/static/js/pipeline_settings.js +121 -0
  419. PipelineManager/static/js/pipeline_text_editor.js +2088 -0
  420. PipelineManager/static/js/plugin_config_modal.js +2827 -0
  421. PipelineManager/static/js/policy_deploy_modal.js +1066 -0
  422. PipelineManager/static/js/show-hint.min.js +1 -0
  423. PipelineManager/static/js/sim_targets.js +380 -0
  424. PipelineManager/static/js/simple-comment-mode.js +56 -0
  425. PipelineManager/static/js/simulation_modal.js +1135 -0
  426. PipelineManager/static/js/simulation_results.js +2778 -0
  427. PipelineManager/static/js/stats_strip.js +231 -0
  428. PipelineManager/static/js/yaml.js +120 -0
  429. PipelineManager/system_policy_defaults.py +279 -0
  430. PipelineManager/templates/components/pipeline_editor/diff_modal.html +127 -0
  431. PipelineManager/templates/components/pipeline_editor/expression_editor.html +160 -0
  432. PipelineManager/templates/components/pipeline_editor/plugin_config_modal.html +119 -0
  433. PipelineManager/templates/components/pipeline_editor/plugin_modal.html +1016 -0
  434. PipelineManager/templates/components/pipeline_editor/simulation_modal.html +394 -0
  435. PipelineManager/templates/components/pipeline_editor/simulation_results.html +123 -0
  436. PipelineManager/templates/components/pipeline_editor/stats_strip.html +123 -0
  437. PipelineManager/templates/components/pipeline_editor/view_code_modal.html +133 -0
  438. PipelineManager/templates/components/pipeline_manager/agent_inspect_content.html +805 -0
  439. PipelineManager/templates/components/pipeline_manager/agent_inspect_modal.html +40 -0
  440. PipelineManager/templates/components/pipeline_manager/agent_policies.html +2421 -0
  441. PipelineManager/templates/components/pipeline_manager/change_policy_modal.html +210 -0
  442. PipelineManager/templates/components/pipeline_manager/collapsible_row.html +11 -0
  443. PipelineManager/templates/components/pipeline_manager/connection_modal.html +1361 -0
  444. PipelineManager/templates/components/pipeline_manager/keystore_modal.html +269 -0
  445. PipelineManager/templates/components/pipeline_manager/logstashyml_guides/centralized_pipeline_management.html +291 -0
  446. PipelineManager/templates/components/pipeline_manager/logstashyml_guides/default.html +166 -0
  447. PipelineManager/templates/components/pipeline_manager/mcp_modal.html +241 -0
  448. PipelineManager/templates/components/pipeline_manager/pipeline_list_content.html +586 -0
  449. PipelineManager/templates/components/pipeline_manager/policy_deploy_modal.html +238 -0
  450. PipelineManager/templates/pipeline_editor.html +1738 -0
  451. PipelineManager/templates/pipeline_graph_editor.html +99 -0
  452. PipelineManager/templates/pipeline_manager.html +584 -0
  453. PipelineManager/templates/pipeline_text_editor.html +350 -0
  454. PipelineManager/urls.py +99 -0
  455. SNMP/__init__.py +0 -0
  456. SNMP/ai_template_generation.py +232 -0
  457. SNMP/apps.py +9 -0
  458. SNMP/assets/device_template_generation/agents/snmp-profile-author.json +15 -0
  459. SNMP/assets/device_template_generation/skills/snmp-catalog.json +9 -0
  460. SNMP/data/authoring_instructions.md +65 -0
  461. SNMP/data/grounding/.gitignore +4 -0
  462. SNMP/data/grounding/build_grounding.py +35 -0
  463. SNMP/data/grounding/grounding.json +1 -0
  464. SNMP/data/grounding/sample_agent_payload.cisco2960x.json +2184 -0
  465. SNMP/data/mib_reference/std_bgp4_mib.json +43 -0
  466. SNMP/data/mib_reference/std_entity_sensors.json +28 -0
  467. SNMP/data/mib_reference/std_host_resources.json +32 -0
  468. SNMP/data/mib_reference/std_ospf_mib.json +55 -0
  469. SNMP/data/mib_reference/std_ucd_linux.json +27 -0
  470. SNMP/data/normalizers.json +103 -0
  471. SNMP/data/official_device_templates/arista_eos.json +24 -0
  472. SNMP/data/official_device_templates/aruba_wireless_controller.json +23 -0
  473. SNMP/data/official_device_templates/brocade_fc_switch.json +20 -0
  474. SNMP/data/official_device_templates/cisco_ios.json +21 -0
  475. SNMP/data/official_device_templates/default.json +13 -0
  476. SNMP/data/official_device_templates/dell_idrac.json +22 -0
  477. SNMP/data/official_device_templates/dell_x1026.json +16 -0
  478. SNMP/data/official_device_templates/dlink_dgs1210_switch.json +19 -0
  479. SNMP/data/official_device_templates/eastpower_ups.json +20 -0
  480. SNMP/data/official_device_templates/eaton_ups.json +22 -0
  481. SNMP/data/official_device_templates/epson_printer.json +18 -0
  482. SNMP/data/official_device_templates/geist_watchdog.json +20 -0
  483. SNMP/data/official_device_templates/generic_linux.json +18 -0
  484. SNMP/data/official_device_templates/generic_ont.json +18 -0
  485. SNMP/data/official_device_templates/generic_ups.json +16 -0
  486. SNMP/data/official_device_templates/hp_laserjet_mfp_m281cdw.json +18 -0
  487. SNMP/data/official_device_templates/hpe_nimble.json +17 -0
  488. SNMP/data/official_device_templates/huawei_ups.json +19 -0
  489. SNMP/data/official_device_templates/ingrasys_ups.json +19 -0
  490. SNMP/data/official_device_templates/isilon_onefs.json +22 -0
  491. SNMP/data/official_device_templates/mellanox_sx6036.json +20 -0
  492. SNMP/data/official_device_templates/netapp_7mode.json +22 -0
  493. SNMP/data/official_device_templates/palo_alto_firewall.json +21 -0
  494. SNMP/data/official_device_templates/phoenixtec_ups.json +18 -0
  495. SNMP/data/official_device_templates/ubiquiti_unifi_ap.json +19 -0
  496. SNMP/data/official_device_templates/ubiquiti_unifi_switch.json +18 -0
  497. SNMP/data/official_device_templates/ubiquiti_unifi_udm.json +19 -0
  498. SNMP/data/official_device_templates/versa_flexvnf_appliance.json +19 -0
  499. SNMP/data/official_profiles/arista_eos.json +16 -0
  500. SNMP/data/official_profiles/aruba_wireless_controller.json +145 -0
  501. SNMP/data/official_profiles/brocade_fibre_channel_switch_fibre_channel_ports.json +35 -0
  502. SNMP/data/official_profiles/brocade_fibre_channel_switch_name_server.json +23 -0
  503. SNMP/data/official_profiles/brocade_fibre_channel_switch_system_metrics.json +36 -0
  504. SNMP/data/official_profiles/cisco_cdp.json +26 -0
  505. SNMP/data/official_profiles/cisco_fans.json +18 -0
  506. SNMP/data/official_profiles/cisco_sensors.json +21 -0
  507. SNMP/data/official_profiles/cisco_system_metrics.json +40 -0
  508. SNMP/data/official_profiles/dell_idrac_cpu.json +19 -0
  509. SNMP/data/official_profiles/dell_idrac_fans.json +20 -0
  510. SNMP/data/official_profiles/dell_idrac_global_status.json +13 -0
  511. SNMP/data/official_profiles/dell_idrac_memory.json +20 -0
  512. SNMP/data/official_profiles/dell_idrac_power_supply.json +19 -0
  513. SNMP/data/official_profiles/dell_idrac_raid_controller.json +19 -0
  514. SNMP/data/official_profiles/dlink_dgs1210.json +15 -0
  515. SNMP/data/official_profiles/dlink_dgs1210_system_metrics.json +38 -0
  516. SNMP/data/official_profiles/eaton_ups.json +40 -0
  517. SNMP/data/official_profiles/geist_environment.json +50 -0
  518. SNMP/data/official_profiles/generic_arp.json +19 -0
  519. SNMP/data/official_profiles/generic_bgp.json +24 -0
  520. SNMP/data/official_profiles/generic_entity_psu.json +26 -0
  521. SNMP/data/official_profiles/generic_entity_sensor.json +22 -0
  522. SNMP/data/official_profiles/generic_host_system_metrics.json +68 -0
  523. SNMP/data/official_profiles/generic_interfaces.json +86 -0
  524. SNMP/data/official_profiles/generic_ip_addr.json +19 -0
  525. SNMP/data/official_profiles/generic_lldp.json +54 -0
  526. SNMP/data/official_profiles/generic_lm_sensors.json +37 -0
  527. SNMP/data/official_profiles/generic_mac_table.json +19 -0
  528. SNMP/data/official_profiles/generic_ont.json +88 -0
  529. SNMP/data/official_profiles/generic_ospf.json +21 -0
  530. SNMP/data/official_profiles/generic_printer_mib.json +48 -0
  531. SNMP/data/official_profiles/generic_rmon.json +38 -0
  532. SNMP/data/official_profiles/generic_system.json +17 -0
  533. SNMP/data/official_profiles/generic_ucd_system_metrics.json +63 -0
  534. SNMP/data/official_profiles/generic_ups_mib.json +154 -0
  535. SNMP/data/official_profiles/hpe_nimble_volumes.json +59 -0
  536. SNMP/data/official_profiles/huawei_ups.json +111 -0
  537. SNMP/data/official_profiles/isilon_performance.json +92 -0
  538. SNMP/data/official_profiles/isilon_protocols.json +77 -0
  539. SNMP/data/official_profiles/isilon_system.json +86 -0
  540. SNMP/data/official_profiles/mellanox_mlnx_os.json +15 -0
  541. SNMP/data/official_profiles/netapp_7mode_data_protection.json +106 -0
  542. SNMP/data/official_profiles/netapp_7mode_disks.json +51 -0
  543. SNMP/data/official_profiles/netapp_7mode_protocols.json +66 -0
  544. SNMP/data/official_profiles/netapp_7mode_system.json +92 -0
  545. SNMP/data/official_profiles/netapp_7mode_volumes.json +166 -0
  546. SNMP/data/official_profiles/paloalto_components.json +36 -0
  547. SNMP/data/official_profiles/paloalto_system.json +15 -0
  548. SNMP/data/official_profiles/traps.json +16 -0
  549. SNMP/data/official_profiles/ubiquiti_unifi_switch.json +18 -0
  550. SNMP/data/official_profiles/ubiquiti_unifi_switch_system.json +14 -0
  551. SNMP/data/official_profiles/ubiquiti_unifi_wireless.json +60 -0
  552. SNMP/data/official_profiles/versa_flexvnf.json +14 -0
  553. SNMP/data/schema.md +650 -0
  554. SNMP/data/schema_reference/snmp_field_schema.md +747 -0
  555. SNMP/data/snmp_template.json +629 -0
  556. SNMP/data/template_profile_context.md +3986 -0
  557. SNMP/inline_grounding.py +77 -0
  558. SNMP/management/__init__.py +1 -0
  559. SNMP/management/commands/__init__.py +1 -0
  560. SNMP/management/commands/generate_template_profile_context.py +272 -0
  561. SNMP/management/commands/load_test_snmp_data.py +240 -0
  562. SNMP/management/commands/sync_snmp_official_data.py +263 -0
  563. SNMP/management/commands/unload_test_snmp_data.py +77 -0
  564. SNMP/migrations/0001_initial.py +101 -0
  565. SNMP/migrations/0002_devicetemplate.py +34 -0
  566. SNMP/migrations/0003_remove_devicetemplate_type_remove_profile_type_and_more.py +31 -0
  567. SNMP/migrations/0004_device_device_template.py +19 -0
  568. SNMP/migrations/0005_devicetemplate_product_profile_product.py +23 -0
  569. SNMP/migrations/0006_alter_devicetemplate_model_and_more.py +28 -0
  570. SNMP/migrations/0007_remove_device_profiles.py +17 -0
  571. SNMP/migrations/0008_devicetemplate_type.py +18 -0
  572. SNMP/migrations/0009_alter_device_device_template.py +19 -0
  573. SNMP/migrations/0010_alter_device_device_template.py +19 -0
  574. SNMP/migrations/0011_network_namespace.py +18 -0
  575. SNMP/migrations/0012_profile_normalizers.py +18 -0
  576. SNMP/migrations/0013_snmpdeploymentstate.py +26 -0
  577. SNMP/migrations/0014_alter_snmpdeploymentstate_last_config_change.py +18 -0
  578. SNMP/migrations/0015_alter_snmpdeploymentstate_last_config_change.py +20 -0
  579. SNMP/migrations/0016_alter_snmpdeploymentstate_last_config_change.py +18 -0
  580. SNMP/migrations/0017_remove_network_logstash_name.py +17 -0
  581. SNMP/migrations/0018_add_official_key.py +39 -0
  582. SNMP/migrations/0019_network_namespace_from_device_template.py +18 -0
  583. SNMP/migrations/0020_device_hostname_alter_device_ip_address_and_more.py +27 -0
  584. SNMP/migrations/0021_device_building_device_latitude_device_longitude_and_more.py +43 -0
  585. SNMP/migrations/0022_alter_device_latitude_alter_device_longitude.py +23 -0
  586. SNMP/migrations/0023_network_agent_connection_network_deployment_mode_and_more.py +30 -0
  587. SNMP/migrations/0024_network_credential_mode.py +18 -0
  588. SNMP/migrations/0025_network_ssl_certificate_authorities.py +18 -0
  589. SNMP/migrations/__init__.py +0 -0
  590. SNMP/models.py +892 -0
  591. SNMP/network_map.py +660 -0
  592. SNMP/overview.py +394 -0
  593. SNMP/snmp_crud.py +6082 -0
  594. SNMP/snmp_grounding.py +146 -0
  595. SNMP/snmp_normalizers.py +594 -0
  596. SNMP/snmp_pipeline_generator.py +1658 -0
  597. SNMP/snmp_test.py +962 -0
  598. SNMP/static/css/snmp.css +33 -0
  599. SNMP/static/images/apc.png +0 -0
  600. SNMP/static/images/arista.png +0 -0
  601. SNMP/static/images/aruba.png +0 -0
  602. SNMP/static/images/brocade.png +0 -0
  603. SNMP/static/images/cisco.png +0 -0
  604. SNMP/static/images/dell.png +0 -0
  605. SNMP/static/images/dlink.png +0 -0
  606. SNMP/static/images/east.png +0 -0
  607. SNMP/static/images/eaton.png +0 -0
  608. SNMP/static/images/epson.png +0 -0
  609. SNMP/static/images/hauwei.png +0 -0
  610. SNMP/static/images/hp.png +0 -0
  611. SNMP/static/images/hpe.png +0 -0
  612. SNMP/static/images/ingrasys.png +0 -0
  613. SNMP/static/images/linux.png +0 -0
  614. SNMP/static/images/mellanox.png +0 -0
  615. SNMP/static/images/netapp.png +0 -0
  616. SNMP/static/images/paloalto.png +0 -0
  617. SNMP/static/images/phoenixtec.png +0 -0
  618. SNMP/static/images/ubiquiti.png +0 -0
  619. SNMP/static/images/unknown.png +0 -0
  620. SNMP/static/images/versa.png +0 -0
  621. SNMP/static/images/vertiv.png +0 -0
  622. SNMP/static/js/ai_device_template_modal.js +1116 -0
  623. SNMP/static/js/credentials_table.js +291 -0
  624. SNMP/static/js/devices_table.js +588 -0
  625. SNMP/static/js/discovered_devices.js +291 -0
  626. SNMP/static/js/network_map.js +1657 -0
  627. SNMP/static/js/networks_table.js +360 -0
  628. SNMP/static/js/onboarding.js +866 -0
  629. SNMP/static/js/overview.js +416 -0
  630. SNMP/static/js/snmp_changes_indicator.js +76 -0
  631. SNMP/static/js/snmp_commit_modal.js +39 -0
  632. SNMP/static/js/snmp_credentials_modal.js +217 -0
  633. SNMP/static/js/snmp_device_template_modal.js +669 -0
  634. SNMP/static/js/snmp_device_visual_preview.js +1707 -0
  635. SNMP/static/js/snmp_devices_modal.js +912 -0
  636. SNMP/static/js/snmp_diff_modal.js +1559 -0
  637. SNMP/static/js/snmp_network_modal.js +940 -0
  638. SNMP/static/js/snmp_profile_modal.js +1212 -0
  639. SNMP/static/js/snmp_profile_modal_helpers.js +17 -0
  640. SNMP/static/js/snmp_test.js +538 -0
  641. SNMP/templates/Credentials.html +325 -0
  642. SNMP/templates/DeviceTemplates.html +1059 -0
  643. SNMP/templates/Devices.html +274 -0
  644. SNMP/templates/Networks.html +469 -0
  645. SNMP/templates/Onboarding.html +521 -0
  646. SNMP/templates/Overview.html +227 -0
  647. SNMP/templates/components/ai_device_template_modal.html +46 -0
  648. SNMP/templates/components/ai_generate_template_content.html +224 -0
  649. SNMP/templates/components/device_template_profile_modal.html +60 -0
  650. SNMP/templates/components/discovered_devices_content.html +86 -0
  651. SNMP/templates/components/discovered_devices_modal.html +43 -0
  652. SNMP/templates/components/gmaps_latlon_modal.html +93 -0
  653. SNMP/templates/components/network_map.html +110 -0
  654. SNMP/templates/components/snmp_commit_modal.html +53 -0
  655. SNMP/templates/components/snmp_credentials_modal.html +189 -0
  656. SNMP/templates/components/snmp_device_modal.html +6 -0
  657. SNMP/templates/components/snmp_device_template_modal.html +129 -0
  658. SNMP/templates/components/snmp_device_visual_preview.html +347 -0
  659. SNMP/templates/components/snmp_devices_modal.html +330 -0
  660. SNMP/templates/components/snmp_diff_modal.html +148 -0
  661. SNMP/templates/components/snmp_network_modal.html +380 -0
  662. SNMP/templates/components/snmp_profile_modal.html +147 -0
  663. SNMP/templates/components/snmp_test_modal.html +398 -0
  664. SNMP/templatetags/__init__.py +0 -0
  665. SNMP/templatetags/snmp_extras.py +17 -0
  666. SNMP/urls.py +94 -0
  667. SNMP/views.py +913 -0
  668. Site/__init__.py +0 -0
  669. Site/apps.py +9 -0
  670. Site/migrations/__init__.py +0 -0
  671. Site/product_ca_views.py +41 -0
  672. Site/static/images/ElasticIcon.png +0 -0
  673. Site/static/images/LoggyIcon.png +0 -0
  674. Site/static/images/LoggyWizardIcon.png +0 -0
  675. Site/static/images/LogstashAgentIcon.png +0 -0
  676. Site/static/images/LogstashIcon.png +0 -0
  677. Site/static/js/base.js +192 -0
  678. Site/static/js/marked.min.js +69 -0
  679. Site/templates/base.html +52 -0
  680. Site/templates/error.html +65 -0
  681. Site/templates/home.html +148 -0
  682. Site/templates/navigation.html +530 -0
  683. Site/templates/popup.html +251 -0
  684. Site/templatetags/__init__.py +0 -0
  685. Site/templatetags/custom_filters.py +36 -0
  686. Site/urls.py +21 -0
  687. Site/views.py +200 -0
  688. Utilities/__init__.py +0 -0
  689. Utilities/apps.py +9 -0
  690. Utilities/data/grok-patterns/LICENSE +202 -0
  691. Utilities/data/grok-patterns/ecs-v1/aws +33 -0
  692. Utilities/data/grok-patterns/ecs-v1/bacula +53 -0
  693. Utilities/data/grok-patterns/ecs-v1/bind +13 -0
  694. Utilities/data/grok-patterns/ecs-v1/bro +30 -0
  695. Utilities/data/grok-patterns/ecs-v1/exim +26 -0
  696. Utilities/data/grok-patterns/ecs-v1/firewalls +111 -0
  697. Utilities/data/grok-patterns/ecs-v1/grok-patterns +95 -0
  698. Utilities/data/grok-patterns/ecs-v1/haproxy +40 -0
  699. Utilities/data/grok-patterns/ecs-v1/httpd +17 -0
  700. Utilities/data/grok-patterns/ecs-v1/java +34 -0
  701. Utilities/data/grok-patterns/ecs-v1/junos +13 -0
  702. Utilities/data/grok-patterns/ecs-v1/linux-syslog +16 -0
  703. Utilities/data/grok-patterns/ecs-v1/maven +1 -0
  704. Utilities/data/grok-patterns/ecs-v1/mcollective +4 -0
  705. Utilities/data/grok-patterns/ecs-v1/mongodb +7 -0
  706. Utilities/data/grok-patterns/ecs-v1/nagios +124 -0
  707. Utilities/data/grok-patterns/ecs-v1/postgresql +2 -0
  708. Utilities/data/grok-patterns/ecs-v1/rails +13 -0
  709. Utilities/data/grok-patterns/ecs-v1/redis +3 -0
  710. Utilities/data/grok-patterns/ecs-v1/ruby +2 -0
  711. Utilities/data/grok-patterns/ecs-v1/squid +6 -0
  712. Utilities/data/grok-patterns/ecs-v1/zeek +33 -0
  713. Utilities/data/grok-patterns/legacy/aws +14 -0
  714. Utilities/data/grok-patterns/legacy/bacula +50 -0
  715. Utilities/data/grok-patterns/legacy/bind +3 -0
  716. Utilities/data/grok-patterns/legacy/bro +13 -0
  717. Utilities/data/grok-patterns/legacy/exim +19 -0
  718. Utilities/data/grok-patterns/legacy/firewalls +91 -0
  719. Utilities/data/grok-patterns/legacy/grok-patterns +95 -0
  720. Utilities/data/grok-patterns/legacy/haproxy +39 -0
  721. Utilities/data/grok-patterns/legacy/httpd +15 -0
  722. Utilities/data/grok-patterns/legacy/java +17 -0
  723. Utilities/data/grok-patterns/legacy/junos +9 -0
  724. Utilities/data/grok-patterns/legacy/linux-syslog +16 -0
  725. Utilities/data/grok-patterns/legacy/maven +1 -0
  726. Utilities/data/grok-patterns/legacy/mcollective +1 -0
  727. Utilities/data/grok-patterns/legacy/mcollective-patterns +4 -0
  728. Utilities/data/grok-patterns/legacy/mongodb +7 -0
  729. Utilities/data/grok-patterns/legacy/nagios +124 -0
  730. Utilities/data/grok-patterns/legacy/postgresql +3 -0
  731. Utilities/data/grok-patterns/legacy/rails +13 -0
  732. Utilities/data/grok-patterns/legacy/redis +3 -0
  733. Utilities/data/grok-patterns/legacy/ruby +2 -0
  734. Utilities/data/grok-patterns/legacy/squid +4 -0
  735. Utilities/dissect.py +302 -0
  736. Utilities/grok.py +412 -0
  737. Utilities/migrations/__init__.py +0 -0
  738. Utilities/static/css/debugger_editor.css +88 -0
  739. Utilities/static/js/debugger_editor.js +93 -0
  740. Utilities/static/js/grok_debugger.js +131 -0
  741. Utilities/templates/dissect_debugger.html +95 -0
  742. Utilities/templates/grok_debugger.html +99 -0
  743. Utilities/urls.py +14 -0
  744. Utilities/views.py +363 -0
  745. logstashui-0.5.5.dev0.dist-info/METADATA +333 -0
  746. logstashui-0.5.5.dev0.dist-info/RECORD +762 -0
  747. logstashui-0.5.5.dev0.dist-info/WHEEL +4 -0
  748. logstashui-0.5.5.dev0.dist-info/entry_points.txt +2 -0
  749. logstashui-0.5.5.dev0.dist-info/licenses/LICENSE.txt +93 -0
  750. logstashui-0.5.5.dev0.dist-info/licenses/NOTICE.txt +2772 -0
  751. theme/__init__.py +0 -0
  752. theme/apps.py +9 -0
  753. theme/package-lock.json +6 -0
  754. theme/static/css/dist/styles.css +2 -0
  755. theme/static/images/favicon.ico +0 -0
  756. theme/static_src/.gitignore +1 -0
  757. theme/static_src/package-lock.json +1930 -0
  758. theme/static_src/package.json +26 -0
  759. theme/static_src/postcss.config.js +7 -0
  760. theme/static_src/src/styles.css +38 -0
  761. theme/static_src/tailwind.config.js +43 -0
  762. theme/templates/base.html +32 -0
@@ -0,0 +1,3746 @@
1
+ //Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
2
+ //or more contributor license agreements. Licensed under the Elastic License;
3
+ //you may not use this file except in compliance with the Elastic License.
4
+
5
+ // Track original content for change detection
6
+ let originalFileContents = {};
7
+ // The form cannot round-trip comments or key order, so logstash.yml also counts as
8
+ // unchanged when it matches the form's own rendering of the saved file.
9
+ let originalFormYml = null;
10
+ let changedFiles = new Set();
11
+ const DRAFT_POLICY_VALUE = '__draft__';
12
+ const SYSTEM_BINARY_PATH = '/usr/share/logstash/bin';
13
+ const DEFAULT_LS_DOWNLOAD_DIR = '/opt/logstash-agent/logstash-versions';
14
+
15
+ function deriveVersionBinaryPath(downloadDir, version) {
16
+ const ver = (version || '').trim();
17
+ if (!ver) return null;
18
+ const root = (downloadDir || DEFAULT_LS_DOWNLOAD_DIR).replace(/\/+$/, '') || DEFAULT_LS_DOWNLOAD_DIR;
19
+ return `${root}/logstash-${ver}/bin`;
20
+ }
21
+
22
+ function isDerivedVersionBinaryPath(path, downloadDir) {
23
+ const p = (path || '').replace(/\/+$/, '');
24
+ if (!p) return false;
25
+ const root = (downloadDir || DEFAULT_LS_DOWNLOAD_DIR).replace(/\/+$/, '') || DEFAULT_LS_DOWNLOAD_DIR;
26
+ const prefix = `${root}/logstash-`;
27
+ const suffix = '/bin';
28
+ if (!p.startsWith(prefix) || !p.endsWith(suffix)) return false;
29
+ const mid = p.slice(prefix.length, p.length - suffix.length);
30
+ return mid.length > 0 && !mid.includes('/');
31
+ }
32
+
33
+ function syncVersionBinaryPath() {
34
+ const sourceEl = document.getElementById('logstashSource');
35
+ const versionEl = document.getElementById('logstashVersion');
36
+ const downloadEl = document.getElementById('logstashDownloadDir');
37
+ const binaryEl = document.getElementById('binaryPath');
38
+ if (!binaryEl) return;
39
+ const source = sourceEl?.value || 'SYSTEM';
40
+ const version = versionEl?.value || '';
41
+ const downloadDir = downloadEl?.value || DEFAULT_LS_DOWNLOAD_DIR;
42
+ const current = binaryEl.value.trim();
43
+ const derived = deriveVersionBinaryPath(downloadDir, version);
44
+ if (source === 'VERSION') {
45
+ if (derived && (!current || current === SYSTEM_BINARY_PATH || isDerivedVersionBinaryPath(current, downloadDir))) {
46
+ binaryEl.value = derived;
47
+ }
48
+ } else if (isDerivedVersionBinaryPath(current, downloadDir)) {
49
+ binaryEl.value = SYSTEM_BINARY_PATH;
50
+ }
51
+ }
52
+
53
+ const POLICY_TYPE_INFO = {
54
+ PACKAGED: {
55
+ hover: 'Distro Logstash as a system service.',
56
+ body: 'Manages the package Logstash unit (logstash + logstash-agent). Typical paths /etc/logstash; agent API 9550, Logstash API 9600. Clone creates a Managed multi-instance policy.',
57
+ },
58
+ MANAGED: {
59
+ hover: 'Isolated agent-owned Logstash instance(s).',
60
+ body: 'Each enrollment gets a managed-N tree under /opt/logstash-agent/managed-N/ and ports 9550+N / 9700+N. Can coexist with Packaged on the same host.',
61
+ },
62
+ SIMULATE: {
63
+ hover: 'Isolated simulation instance(s).',
64
+ body: 'Each enrollment gets a simulate-N tree under /opt/logstash-agent/simulate-N/ and ports 9500+N / 9560+N. For pipeline simulation, not production.',
65
+ },
66
+ };
67
+
68
+ function policyRoleClassName(ptype) {
69
+ let t = (ptype || 'PACKAGED').toUpperCase();
70
+ if (t === 'DEFAULT') t = 'PACKAGED';
71
+ if (t === 'SIMULATE') return 'role-simulate';
72
+ if (t === 'EMBEDDED') return 'role-embedded';
73
+ if (t === 'MANAGED') return 'role-managed';
74
+ if (t === 'PACKAGED') return 'role-packaged';
75
+ return 'role-default';
76
+ }
77
+
78
+ function isDraftPolicyOption(opt) {
79
+ return opt?.dataset?.isDraft === 'true' || opt?.value === DRAFT_POLICY_VALUE;
80
+ }
81
+
82
+ // Notification buckets — merged before updating the bell indicator
83
+ let logstashNotifications = [];
84
+ let jvmNotifications = [];
85
+
86
+ function refreshBellNotifications() {
87
+ updateNotificationIndicator([...logstashNotifications, ...jvmNotifications]);
88
+ }
89
+
90
+ // Toggle advanced settings sections
91
+ function toggleAdvanced(sectionId) {
92
+ const section = document.getElementById(sectionId);
93
+ const icon = document.getElementById(sectionId + '-icon');
94
+
95
+ if (section.classList.contains('hidden')) {
96
+ section.classList.remove('hidden');
97
+ icon.classList.add('rotate-90');
98
+ } else {
99
+ section.classList.add('hidden');
100
+ icon.classList.remove('rotate-90');
101
+ }
102
+ }
103
+
104
+ // Check for configuration issues and show notifications
105
+ function checkConfigNotifications() {
106
+ const logsPathGlobal = document.querySelector('[name="path.logs"]')?.value || '';
107
+ const logsPathSetting = document.getElementById('logsPath')?.value || '';
108
+ const logLevel = document.querySelector('[name="log.level"]')?.value || '';
109
+ const logFormat = document.querySelector('[name="log.format"]')?.value || '';
110
+ const configReloadAutomatic = document.querySelector('[name="config.reload.automatic"]')?.value || '';
111
+ const configReloadInterval = document.querySelector('[name="config.reload.interval"]')?.value || '';
112
+ const apiEnabled = document.querySelector('[name="api.enabled"]')?.value || '';
113
+ const apiHost = document.querySelector('[name="api.http.host"]')?.value || '';
114
+ const apiPort = document.querySelector('[name="api.http.port"]')?.value || '';
115
+ const unsafeShutdown = document.querySelector('[name="pipeline.unsafe_shutdown"]')?.value || '';
116
+ const allowSuperuser = document.querySelector('[name="allow_superuser"]')?.value || '';
117
+ const configDebug = document.querySelector('[name="config.debug"]')?.value || '';
118
+ const batchDelay = document.querySelector('[name="pipeline.batch.delay"]')?.value || '';
119
+ const cpmEnabled = document.querySelector('[name="xpack.management.enabled"]')?.value || '';
120
+
121
+ // console.log('Checking notifications - Global:', logsPathGlobal, 'Setting:', logsPathSetting);
122
+
123
+ // Check for CPM enabled - show warning on Pipelines tab if true
124
+ const cpmPipelineWarning = document.getElementById('cpmPipelineWarning');
125
+ if (cpmPipelineWarning) {
126
+ if (cpmEnabled === 'true') {
127
+ cpmPipelineWarning.classList.remove('hidden');
128
+ } else {
129
+ cpmPipelineWarning.classList.add('hidden');
130
+ }
131
+ }
132
+
133
+ const unsafeShutdownNotification = document.getElementById('unsafeShutdownNotification');
134
+ const allowSuperuserNotification = document.getElementById('allowSuperuserNotification');
135
+ const configDebugNotification = document.getElementById('configDebugNotification');
136
+ const batchDelayNotification = document.getElementById('batchDelayNotification');
137
+ const notificationsContainer = document.getElementById('notificationsContainer');
138
+
139
+ // --- Requirements tile (mirrors Default guide validation exactly) ---
140
+ const hasMismatch = logsPathSetting && logsPathGlobal !== logsPathSetting;
141
+ const needsLogLevel = logLevel !== 'info';
142
+ const needsLogFormat = logFormat !== 'json';
143
+ const needsReloadAuto = configReloadAutomatic !== 'true';
144
+ const needsReloadInterval= !configReloadInterval.trim();
145
+ const needsApiEnabled = apiEnabled === 'false';
146
+ const needsApiHost = !apiHost.trim();
147
+ const needsApiPort = !apiPort.trim();
148
+ const unmetCount = [hasMismatch, needsLogLevel, needsLogFormat, needsReloadAuto,
149
+ needsReloadInterval, needsApiEnabled, needsApiHost, needsApiPort]
150
+ .filter(Boolean).length;
151
+
152
+ const requirementsTile = document.getElementById('requirementsTile');
153
+ const requirementsBadge = document.getElementById('requirementsBadge');
154
+ const requirementsIcon = document.getElementById('requirementsIcon');
155
+ const requirementsLabel = document.getElementById('requirementsLabel');
156
+
157
+ if (requirementsTile) {
158
+ if (unmetCount > 0) {
159
+ requirementsTile.classList.remove('requirement-tile-ok');
160
+ requirementsTile.classList.add('requirement-tile-fail');
161
+ if (requirementsIcon) {
162
+ requirementsIcon.innerHTML = '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z" />';
163
+ }
164
+ } else {
165
+ requirementsTile.classList.remove('requirement-tile-fail');
166
+ requirementsTile.classList.add('requirement-tile-ok');
167
+ if (requirementsIcon) {
168
+ requirementsIcon.innerHTML = '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />';
169
+ }
170
+ }
171
+ }
172
+ if (requirementsBadge) {
173
+ if (unmetCount > 0) {
174
+ requirementsBadge.textContent = unmetCount + ' unmet';
175
+ requirementsBadge.classList.remove('hidden');
176
+ } else {
177
+ requirementsBadge.classList.add('hidden');
178
+ }
179
+ }
180
+
181
+ // Check for unsafe shutdown - show if set to true
182
+ const hasUnsafeShutdown = unsafeShutdown === 'true';
183
+
184
+ if (hasUnsafeShutdown) {
185
+ // console.log('Unsafe shutdown enabled - showing notification');
186
+ unsafeShutdownNotification?.classList.remove('hidden');
187
+ notificationsContainer?.classList.remove('hidden');
188
+ } else {
189
+ // console.log('Unsafe shutdown not enabled - hiding notification');
190
+ unsafeShutdownNotification?.classList.add('hidden');
191
+ }
192
+
193
+ // Check for allow superuser - show if set to true
194
+ const hasAllowSuperuser = allowSuperuser === 'true';
195
+
196
+ if (hasAllowSuperuser) {
197
+ // console.log('Allow superuser enabled - showing notification');
198
+ allowSuperuserNotification?.classList.remove('hidden');
199
+ notificationsContainer?.classList.remove('hidden');
200
+ } else {
201
+ // console.log('Allow superuser not enabled - hiding notification');
202
+ allowSuperuserNotification?.classList.add('hidden');
203
+ }
204
+
205
+ // Check for config debug - show if set to true
206
+ const hasConfigDebug = configDebug === 'true';
207
+
208
+ if (hasConfigDebug) {
209
+ // console.log('Config debug enabled - showing notification');
210
+ configDebugNotification?.classList.remove('hidden');
211
+ notificationsContainer?.classList.remove('hidden');
212
+ } else {
213
+ // console.log('Config debug not enabled - hiding notification');
214
+ configDebugNotification?.classList.add('hidden');
215
+ }
216
+
217
+ // Check for batch delay - show if value is set (not empty/default)
218
+ const hasBatchDelay = batchDelay && batchDelay.trim() !== '';
219
+
220
+ if (hasBatchDelay) {
221
+ // console.log('Batch delay modified - showing notification');
222
+ batchDelayNotification?.classList.remove('hidden');
223
+ notificationsContainer?.classList.remove('hidden');
224
+ } else {
225
+ // console.log('Batch delay not modified - hiding notification');
226
+ batchDelayNotification?.classList.add('hidden');
227
+ }
228
+
229
+ // Hide container if no notifications are visible
230
+ const hasVisibleNotifications = notificationsContainer?.querySelector('.p-3:not(.hidden)');
231
+ if (!hasVisibleNotifications) {
232
+ notificationsContainer?.classList.add('hidden');
233
+ }
234
+
235
+ // Collect active notifications for indicator
236
+ const activeNotifications = [];
237
+ if (unmetCount > 0) {
238
+ activeNotifications.push({
239
+ type: 'warning',
240
+ title: 'Requirements',
241
+ message: unmetCount + ' unmet requirement' + (unmetCount > 1 ? 's' : '')
242
+ });
243
+ }
244
+ if (!unsafeShutdownNotification?.classList.contains('hidden')) {
245
+ activeNotifications.push({
246
+ type: 'error',
247
+ title: 'Unsafe Shutdown Enabled',
248
+ message: 'This could result in data loss'
249
+ });
250
+ }
251
+ if (!allowSuperuserNotification?.classList.contains('hidden')) {
252
+ activeNotifications.push({
253
+ type: 'warning',
254
+ title: 'Allow Superuser Enabled',
255
+ message: 'Not recommended for security purposes'
256
+ });
257
+ }
258
+ if (!configDebugNotification?.classList.contains('hidden')) {
259
+ activeNotifications.push({
260
+ type: 'warning',
261
+ title: 'Config Debug Enabled',
262
+ message: 'Prints compiled pipeline config to logs'
263
+ });
264
+ }
265
+ if (!batchDelayNotification?.classList.contains('hidden')) {
266
+ activeNotifications.push({
267
+ type: 'warning',
268
+ title: 'Batch Delay Modified',
269
+ message: 'Not typically recommended to change'
270
+ });
271
+ }
272
+
273
+ // Update notification indicator
274
+ logstashNotifications = activeNotifications;
275
+ refreshBellNotifications();
276
+ }
277
+
278
+ // Check and update path permission notifications
279
+ function checkPathPermissionNotifications() {
280
+ const settingsPathField = document.getElementById('settingsPath');
281
+ const logsPathField = document.getElementById('logsPath');
282
+ const binaryPathField = document.getElementById('binaryPath');
283
+ const settingsPathNotification = document.getElementById('settingsPathNotification');
284
+ const logsPathNotification = document.getElementById('logsPathNotification');
285
+ const binaryPathNotification = document.getElementById('binaryPathNotification');
286
+
287
+ if (settingsPathField && settingsPathNotification) {
288
+ const settingsPath = settingsPathField.value.trim();
289
+ if (settingsPath && settingsPath !== '/etc/logstash' && settingsPath !== '/etc/logstash/') {
290
+ settingsPathNotification.dataset.tip = `${settingsPath} will need to allow read and write access to the 'logstash' user`;
291
+ settingsPathNotification.classList.remove('hidden');
292
+ } else {
293
+ settingsPathNotification.classList.add('hidden');
294
+ }
295
+ }
296
+
297
+ if (logsPathField && logsPathNotification) {
298
+ const logsPath = logsPathField.value.trim();
299
+ if (logsPath && logsPath !== '/var/log/logstash' && logsPath !== '/var/log/logstash/') {
300
+ logsPathNotification.dataset.tip = `${logsPath} will need to allow read access to the 'logstash' user`;
301
+ logsPathNotification.classList.remove('hidden');
302
+ } else {
303
+ logsPathNotification.classList.add('hidden');
304
+ }
305
+ }
306
+
307
+ if (binaryPathField && binaryPathNotification) {
308
+ const binaryPath = binaryPathField.value.trim();
309
+ if (binaryPath && binaryPath !== '/usr/share/logstash/bin' && binaryPath !== '/usr/share/logstash/bin/') {
310
+ binaryPathNotification.dataset.tip = `${binaryPath} will need to allow the 'logstash' user to execute its binaries`;
311
+ binaryPathNotification.classList.remove('hidden');
312
+ } else {
313
+ binaryPathNotification.classList.add('hidden');
314
+ }
315
+ }
316
+ }
317
+
318
+ // Update the undeployed changes count in the stats strip
319
+ function updateUndeployedChangesInStatsStrip(count) {
320
+ const pendingEl = document.getElementById('statPendingChanges');
321
+ if (pendingEl) {
322
+ if (count === 0) {
323
+ pendingEl.textContent = 'None';
324
+ } else {
325
+ pendingEl.textContent = `${count} section${count !== 1 ? 's' : ''}`;
326
+ }
327
+ }
328
+ }
329
+
330
+ // Update deploy button indicator based on undeployed changes count
331
+ function updateDeployButtonIndicator(count) {
332
+ const indicator = document.getElementById('deployBtnIndicator');
333
+ const indicatorText = document.getElementById('deployBtnIndicatorText');
334
+
335
+ if (!indicator || !indicatorText) return;
336
+
337
+ if (count > 0) {
338
+ indicatorText.textContent = 'Undeployed changes';
339
+ indicator.classList.remove('hidden');
340
+ } else {
341
+ indicator.classList.add('hidden');
342
+ }
343
+
344
+ // Also update the stats strip
345
+ updateUndeployedChangesInStatsStrip(count);
346
+ }
347
+
348
+ // Fix logs path mismatch by syncing FROM config TO global setting
349
+ function fixLogsPathMismatch() {
350
+ const logsPathGlobal = document.querySelector('[name="path.logs"]');
351
+ const logsPathSetting = document.getElementById('logsPath');
352
+
353
+ if (logsPathGlobal && logsPathSetting) {
354
+ // Copy FROM config (logsPath) TO global setting (path.logs)
355
+ logsPathGlobal.value = logsPathSetting.value;
356
+
357
+ // Trigger change event to apply any UI effects
358
+ logsPathGlobal.dispatchEvent(new Event('input', { bubbles: true }));
359
+ logsPathGlobal.dispatchEvent(new Event('change', { bubbles: true }));
360
+
361
+ // Recheck notifications
362
+ checkConfigNotifications();
363
+
364
+ // Show success toast
365
+ showToast('Global logs path updated to match config', 'success');
366
+ }
367
+ }
368
+
369
+ // Fix log level and format by setting to optimal values for logstashui
370
+ function fixLogLevelFormat() {
371
+ const logLevelField = document.querySelector('[name="log.level"]');
372
+ const logFormatField = document.querySelector('[name="log.format"]');
373
+
374
+ if (logLevelField) {
375
+ logLevelField.value = 'info';
376
+ logLevelField.dispatchEvent(new Event('input', { bubbles: true }));
377
+ logLevelField.dispatchEvent(new Event('change', { bubbles: true }));
378
+ }
379
+
380
+ if (logFormatField) {
381
+ logFormatField.value = 'json';
382
+ logFormatField.dispatchEvent(new Event('input', { bubbles: true }));
383
+ logFormatField.dispatchEvent(new Event('change', { bubbles: true }));
384
+ }
385
+
386
+ // Recheck notifications
387
+ checkConfigNotifications();
388
+
389
+ // Show success toast
390
+ showToast('Log level set to Info and format set to JSON', 'success');
391
+ }
392
+
393
+ // Fix unsafe shutdown by setting it back to default (false)
394
+ function fixUnsafeShutdown() {
395
+ const unsafeShutdownField = document.querySelector('[name="pipeline.unsafe_shutdown"]');
396
+
397
+ if (unsafeShutdownField) {
398
+ unsafeShutdownField.value = '';
399
+ unsafeShutdownField.dispatchEvent(new Event('input', { bubbles: true }));
400
+ unsafeShutdownField.dispatchEvent(new Event('change', { bubbles: true }));
401
+ }
402
+
403
+ // Recheck notifications
404
+ checkConfigNotifications();
405
+
406
+ // Show success toast
407
+ showToast('Unsafe shutdown set to default (false)', 'success');
408
+ }
409
+
410
+ // Fix allow superuser by setting it back to default (false)
411
+ function fixAllowSuperuser() {
412
+ const allowSuperuserField = document.querySelector('[name="allow_superuser"]');
413
+
414
+ if (allowSuperuserField) {
415
+ allowSuperuserField.value = '';
416
+ allowSuperuserField.dispatchEvent(new Event('input', { bubbles: true }));
417
+ allowSuperuserField.dispatchEvent(new Event('change', { bubbles: true }));
418
+ }
419
+
420
+ // Recheck notifications
421
+ checkConfigNotifications();
422
+
423
+ // Show success toast
424
+ showToast('Allow superuser set to default (false)', 'success');
425
+ }
426
+
427
+ // Fix config debug by setting it back to default (false)
428
+ function fixConfigDebug() {
429
+ const configDebugField = document.querySelector('[name="config.debug"]');
430
+
431
+ if (configDebugField) {
432
+ configDebugField.value = '';
433
+ configDebugField.dispatchEvent(new Event('input', { bubbles: true }));
434
+ configDebugField.dispatchEvent(new Event('change', { bubbles: true }));
435
+ }
436
+
437
+ // Recheck notifications
438
+ checkConfigNotifications();
439
+
440
+ // Show success toast
441
+ showToast('Config debug set to default (false)', 'success');
442
+ }
443
+
444
+ // Fix batch delay by clearing it to use the default
445
+ function fixBatchDelay() {
446
+ const batchDelayField = document.querySelector('[name="pipeline.batch.delay"]');
447
+
448
+ if (batchDelayField) {
449
+ batchDelayField.value = '';
450
+ batchDelayField.dispatchEvent(new Event('input', { bubbles: true }));
451
+ batchDelayField.dispatchEvent(new Event('change', { bubbles: true }));
452
+ }
453
+
454
+ // Recheck notifications
455
+ checkConfigNotifications();
456
+
457
+ // Show success toast
458
+ showToast('Batch delay set to default (50ms)', 'success');
459
+ }
460
+
461
+ // Convert form fields to YAML content
462
+ function formToYml() {
463
+ // console.log('Converting form to YAML...');
464
+
465
+ const config = {};
466
+
467
+ // Helper function to set nested property value
468
+ function setNestedValue(obj, path, value) {
469
+ const keys = path.split('.');
470
+ const lastKey = keys.pop();
471
+ const target = keys.reduce((current, key) => {
472
+ if (!current[key]) current[key] = {};
473
+ return current[key];
474
+ }, obj);
475
+ target[lastKey] = value;
476
+ }
477
+
478
+ // Helper function to get all form field values
479
+ function getFormFieldValue(fieldName) {
480
+ const field = document.querySelector(`[name="${fieldName}"]`);
481
+ if (!field) return null;
482
+
483
+ // For select/dropdown fields, check if value is empty or default placeholder
484
+ if (field.tagName === 'SELECT') {
485
+ const value = field.value.trim();
486
+ // Skip if empty or starts with "Default"
487
+ if (!value || value === '' || value.startsWith('Default')) return null;
488
+
489
+ // Parse boolean values
490
+ if (value === 'true') return true;
491
+ if (value === 'false') return false;
492
+
493
+ // Return the actual value
494
+ return value;
495
+ }
496
+
497
+ // For other fields, skip if empty
498
+ if (!field.value || field.value.trim() === '') return null;
499
+
500
+ // Handle different field types
501
+ if (field.type === 'number') {
502
+ return parseInt(field.value, 10);
503
+ } else if (field.type === 'checkbox') {
504
+ return field.checked;
505
+ } else if (field.type === 'text' || field.type === 'password') {
506
+ const value = field.value.trim();
507
+ // Try to parse as boolean
508
+ if (value === 'true') return true;
509
+ if (value === 'false') return false;
510
+ // Try to parse as number
511
+ if (!isNaN(value) && value !== '') {
512
+ const num = parseFloat(value);
513
+ if (num.toString() === value) return num;
514
+ }
515
+ return value;
516
+ }
517
+ return field.value.trim();
518
+ }
519
+
520
+ // Helper function to parse comma-separated values into array
521
+ function parseArrayField(value) {
522
+ if (!value) return null;
523
+ return value.split(',').map(v => v.trim()).filter(v => v !== '');
524
+ }
525
+
526
+ // Collect all form fields and their values
527
+ const fieldMappings = [
528
+ // Node Identity
529
+ 'node.name',
530
+ // Data Path
531
+ 'path.data',
532
+ // Pipeline Settings
533
+ 'pipeline.id',
534
+ 'pipeline.workers',
535
+ 'pipeline.batch.size',
536
+ 'pipeline.batch.delay',
537
+ 'pipeline.batch.output_chunking.growth_threshold_factor',
538
+ 'pipeline.batch.metrics.sampling_mode',
539
+ 'pipeline.unsafe_shutdown',
540
+ 'pipeline.ordered',
541
+ 'pipeline.ecs_compatibility',
542
+ 'pipeline.separate_logs',
543
+ 'pipeline.buffer.type',
544
+ // API Settings
545
+ 'api.enabled',
546
+ 'api.http.host',
547
+ 'api.http.port',
548
+ 'api.environment',
549
+ 'api.ssl.enabled',
550
+ 'api.ssl.keystore.path',
551
+ 'api.ssl.keystore.password',
552
+ 'api.auth.type',
553
+ 'api.auth.basic.username',
554
+ 'api.auth.basic.password',
555
+ 'api.auth.basic.password_policy.mode',
556
+ // Queue Settings
557
+ 'queue.type',
558
+ 'path.queue',
559
+ 'queue.page_capacity',
560
+ 'queue.max_events',
561
+ 'queue.max_bytes',
562
+ 'queue.checkpoint.acks',
563
+ 'queue.checkpoint.writes',
564
+ 'queue.compression',
565
+ // Dead Letter Queue
566
+ 'dead_letter_queue.enable',
567
+ 'dead_letter_queue.max_bytes',
568
+ 'path.dead_letter_queue',
569
+ 'dead_letter_queue.flush_interval',
570
+ 'dead_letter_queue.storage_policy',
571
+ 'dead_letter_queue.retain.age',
572
+ // Pipeline Configuration
573
+ 'path.config',
574
+ 'config.string',
575
+ 'config.test_and_exit',
576
+ 'config.reload.automatic',
577
+ 'config.reload.interval',
578
+ 'config.debug',
579
+ 'config.support_escapes',
580
+ // Logging Settings
581
+ 'log.level',
582
+ 'log.format',
583
+ 'log.format.json.fix_duplicate_message_fields',
584
+ 'path.logs',
585
+ // Other Settings
586
+ 'allow_superuser',
587
+ // X-Pack Monitoring
588
+ 'xpack.monitoring.enabled',
589
+ 'xpack.monitoring.collection.interval',
590
+ 'xpack.monitoring.elasticsearch.cloud_id',
591
+ 'xpack.monitoring.elasticsearch.api_key',
592
+ 'xpack.monitoring.elasticsearch.username',
593
+ 'xpack.monitoring.elasticsearch.password',
594
+ 'xpack.monitoring.elasticsearch.cloud_auth',
595
+ 'xpack.monitoring.elasticsearch.ssl.certificate_authority',
596
+ 'xpack.monitoring.elasticsearch.ssl.ca_trusted_fingerprint',
597
+ 'xpack.monitoring.elasticsearch.ssl.truststore.path',
598
+ 'xpack.monitoring.elasticsearch.ssl.truststore.password',
599
+ 'xpack.monitoring.elasticsearch.ssl.keystore.path',
600
+ 'xpack.monitoring.elasticsearch.ssl.keystore.password',
601
+ 'xpack.monitoring.elasticsearch.ssl.certificate',
602
+ 'xpack.monitoring.elasticsearch.ssl.key',
603
+ 'xpack.monitoring.elasticsearch.ssl.verification_mode',
604
+ 'xpack.monitoring.elasticsearch.sniffing',
605
+ 'xpack.monitoring.allow_legacy_collection',
606
+ 'xpack.monitoring.collection.pipeline.details.enabled',
607
+ // X-Pack Management
608
+ 'xpack.management.enabled',
609
+ 'xpack.management.logstash.poll_interval',
610
+ 'xpack.management.elasticsearch.cloud_id',
611
+ 'xpack.management.elasticsearch.api_key',
612
+ 'xpack.management.elasticsearch.username',
613
+ 'xpack.management.elasticsearch.password',
614
+ 'xpack.management.elasticsearch.cloud_auth',
615
+ 'xpack.management.elasticsearch.ssl.certificate_authority',
616
+ 'xpack.management.elasticsearch.ssl.ca_trusted_fingerprint',
617
+ 'xpack.management.elasticsearch.ssl.truststore.path',
618
+ 'xpack.management.elasticsearch.ssl.truststore.password',
619
+ 'xpack.management.elasticsearch.ssl.keystore.path',
620
+ 'xpack.management.elasticsearch.ssl.keystore.password',
621
+ 'xpack.management.elasticsearch.ssl.certificate',
622
+ 'xpack.management.elasticsearch.ssl.key',
623
+ 'xpack.management.elasticsearch.ssl.verification_mode',
624
+ 'xpack.management.elasticsearch.sniffing',
625
+ // X-Pack GeoIP
626
+ 'xpack.geoip.downloader.enabled',
627
+ 'xpack.geoip.downloader.endpoint'
628
+ ];
629
+
630
+ // Process each field
631
+ fieldMappings.forEach(fieldName => {
632
+ const value = getFormFieldValue(fieldName);
633
+ if (value !== null) {
634
+ setNestedValue(config, fieldName, value);
635
+ }
636
+ });
637
+
638
+ // Handle array fields separately
639
+ const arrayFields = [
640
+ { name: 'api.ssl.supported_protocols', path: 'api.ssl.supported_protocols' },
641
+ { name: 'path.plugins', path: 'path.plugins' },
642
+ { name: 'xpack.monitoring.elasticsearch.hosts', path: 'xpack.monitoring.elasticsearch.hosts' },
643
+ { name: 'xpack.monitoring.elasticsearch.proxy', path: 'xpack.monitoring.elasticsearch.proxy' },
644
+ { name: 'xpack.monitoring.elasticsearch.ssl.cipher_suites', path: 'xpack.monitoring.elasticsearch.ssl.cipher_suites' },
645
+ { name: 'xpack.management.pipeline.id', path: 'xpack.management.pipeline.id' },
646
+ { name: 'xpack.management.elasticsearch.hosts', path: 'xpack.management.elasticsearch.hosts' },
647
+ { name: 'xpack.management.elasticsearch.proxy', path: 'xpack.management.elasticsearch.proxy' },
648
+ { name: 'xpack.management.elasticsearch.ssl.cipher_suites', path: 'xpack.management.elasticsearch.ssl.cipher_suites' }
649
+ ];
650
+
651
+ arrayFields.forEach(({ name, path }) => {
652
+ const field = document.querySelector(`[name="${name}"]`);
653
+ if (field && field.value && field.value.trim() !== '') {
654
+ const arrayValue = parseArrayField(field.value);
655
+ if (arrayValue && arrayValue.length > 0) {
656
+ setNestedValue(config, path, arrayValue);
657
+ }
658
+ }
659
+ });
660
+
661
+ // Check if config is empty (no fields were populated)
662
+ const isEmpty = Object.keys(config).length === 0;
663
+
664
+ if (isEmpty) {
665
+ // If form is empty, preserve the original YAML content instead of replacing with {}
666
+ // console.log('Form is empty, preserving original YAML content');
667
+ return window.policyFileContents?.['logstash.yml'] || '';
668
+ }
669
+
670
+ // Convert to YAML using js-yaml
671
+ const yamlContent = jsyaml.dump(config, {
672
+ indent: 2,
673
+ lineWidth: -1,
674
+ noRefs: true,
675
+ sortKeys: false
676
+ });
677
+
678
+ // console.log('Form converted to YAML successfully');
679
+ return yamlContent;
680
+ }
681
+
682
+ // Parse YAML content and populate form fields
683
+ function parseYmlToForm(ymlContent) {
684
+ if (!ymlContent || ymlContent.trim() === '') {
685
+ // console.log('No YAML content to parse');
686
+ return;
687
+ }
688
+
689
+ // console.log('Starting YAML parsing...');
690
+ // console.log('YAML content length:', ymlContent.length);
691
+
692
+ // Clear all form fields first to ensure commented-out values are removed
693
+ const allFormFields = document.querySelectorAll('#formModeEditor input, #formModeEditor select, #formModeEditor textarea');
694
+ allFormFields.forEach(field => {
695
+ field.value = '';
696
+ // Reset original value to prevent purple glow on empty fields
697
+ field.dataset.originalValue = '';
698
+ field.classList.remove('field-modified');
699
+ });
700
+
701
+ try {
702
+ // Parse YAML using js-yaml library
703
+ const config = jsyaml.load(ymlContent);
704
+
705
+ // console.log('Parsed YAML config:', config);
706
+
707
+ if (!config || typeof config !== 'object') {
708
+ console.warn('Invalid YAML configuration - not an object');
709
+ return;
710
+ }
711
+
712
+ // Helper function to safely get nested property value
713
+ // First try direct key access (for flat YAML with dot notation keys)
714
+ // Then try nested path traversal (for hierarchical YAML)
715
+ function getNestedValue(obj, path) {
716
+ // Try direct key access first (e.g., obj['node.name'])
717
+ if (obj.hasOwnProperty(path)) {
718
+ return obj[path];
719
+ }
720
+ // Fall back to nested traversal (e.g., obj.node.name)
721
+ return path.split('.').reduce((current, key) => current?.[key], obj);
722
+ }
723
+
724
+ // Helper function to set form field value
725
+ function setFormField(fieldName, value) {
726
+ if (value === null || value === undefined) return;
727
+
728
+ const field = document.querySelector(`[name="${fieldName}"]`);
729
+ if (field) {
730
+ field.value = value;
731
+ // console.log(`Set field ${fieldName} = ${value}`);
732
+ // Trigger change event to apply modified styling
733
+ field.dispatchEvent(new Event('input', { bubbles: true }));
734
+ field.dispatchEvent(new Event('change', { bubbles: true }));
735
+ } else {
736
+ console.warn(`Field not found: ${fieldName}`);
737
+ }
738
+ }
739
+
740
+ // Node Identity
741
+ setFormField('node.name', getNestedValue(config, 'node.name'));
742
+
743
+ // Data Path
744
+ setFormField('path.data', getNestedValue(config, 'path.data'));
745
+
746
+ // Pipeline Settings
747
+ setFormField('pipeline.id', getNestedValue(config, 'pipeline.id'));
748
+ setFormField('pipeline.workers', getNestedValue(config, 'pipeline.workers'));
749
+ setFormField('pipeline.batch.size', getNestedValue(config, 'pipeline.batch.size'));
750
+ setFormField('pipeline.batch.delay', getNestedValue(config, 'pipeline.batch.delay'));
751
+ setFormField('pipeline.batch.output_chunking.growth_threshold_factor', getNestedValue(config, 'pipeline.batch.output_chunking.growth_threshold_factor'));
752
+ setFormField('pipeline.batch.metrics.sampling_mode', getNestedValue(config, 'pipeline.batch.metrics.sampling_mode'));
753
+ setFormField('pipeline.unsafe_shutdown', getNestedValue(config, 'pipeline.unsafe_shutdown'));
754
+ setFormField('pipeline.ordered', getNestedValue(config, 'pipeline.ordered'));
755
+ setFormField('pipeline.ecs_compatibility', getNestedValue(config, 'pipeline.ecs_compatibility'));
756
+ setFormField('pipeline.separate_logs', getNestedValue(config, 'pipeline.separate_logs'));
757
+ setFormField('pipeline.buffer.type', getNestedValue(config, 'pipeline.buffer.type'));
758
+
759
+ // API Settings
760
+ setFormField('api.enabled', getNestedValue(config, 'api.enabled'));
761
+ setFormField('api.http.host', getNestedValue(config, 'api.http.host'));
762
+ setFormField('api.http.port', getNestedValue(config, 'api.http.port'));
763
+ setFormField('api.environment', getNestedValue(config, 'api.environment'));
764
+ setFormField('api.ssl.enabled', getNestedValue(config, 'api.ssl.enabled'));
765
+ setFormField('api.ssl.keystore.path', getNestedValue(config, 'api.ssl.keystore.path'));
766
+ setFormField('api.ssl.keystore.password', getNestedValue(config, 'api.ssl.keystore.password'));
767
+
768
+ // Handle api.ssl.supported_protocols array
769
+ const sslProtocols = getNestedValue(config, 'api.ssl.supported_protocols');
770
+ if (Array.isArray(sslProtocols)) {
771
+ setFormField('api.ssl.supported_protocols', sslProtocols.join(', '));
772
+ }
773
+
774
+ setFormField('api.auth.type', getNestedValue(config, 'api.auth.type'));
775
+ setFormField('api.auth.basic.username', getNestedValue(config, 'api.auth.basic.username'));
776
+ setFormField('api.auth.basic.password', getNestedValue(config, 'api.auth.basic.password'));
777
+ setFormField('api.auth.basic.password_policy.mode', getNestedValue(config, 'api.auth.basic.password_policy.mode'));
778
+
779
+ // Queue Settings
780
+ setFormField('queue.type', getNestedValue(config, 'queue.type'));
781
+ setFormField('path.queue', getNestedValue(config, 'path.queue'));
782
+ setFormField('queue.page_capacity', getNestedValue(config, 'queue.page_capacity'));
783
+ setFormField('queue.max_events', getNestedValue(config, 'queue.max_events'));
784
+ setFormField('queue.max_bytes', getNestedValue(config, 'queue.max_bytes'));
785
+ setFormField('queue.checkpoint.acks', getNestedValue(config, 'queue.checkpoint.acks'));
786
+ setFormField('queue.checkpoint.writes', getNestedValue(config, 'queue.checkpoint.writes'));
787
+ setFormField('queue.compression', getNestedValue(config, 'queue.compression'));
788
+
789
+ // Dead Letter Queue
790
+ setFormField('dead_letter_queue.enable', getNestedValue(config, 'dead_letter_queue.enable'));
791
+ setFormField('dead_letter_queue.max_bytes', getNestedValue(config, 'dead_letter_queue.max_bytes'));
792
+ setFormField('path.dead_letter_queue', getNestedValue(config, 'path.dead_letter_queue'));
793
+ setFormField('dead_letter_queue.flush_interval', getNestedValue(config, 'dead_letter_queue.flush_interval'));
794
+ setFormField('dead_letter_queue.storage_policy', getNestedValue(config, 'dead_letter_queue.storage_policy'));
795
+ setFormField('dead_letter_queue.retain.age', getNestedValue(config, 'dead_letter_queue.retain.age'));
796
+
797
+ // Pipeline Configuration
798
+ setFormField('path.config', getNestedValue(config, 'path.config'));
799
+ setFormField('config.string', getNestedValue(config, 'config.string'));
800
+ setFormField('config.test_and_exit', getNestedValue(config, 'config.test_and_exit'));
801
+ setFormField('config.reload.automatic', getNestedValue(config, 'config.reload.automatic'));
802
+ setFormField('config.reload.interval', getNestedValue(config, 'config.reload.interval'));
803
+ setFormField('config.debug', getNestedValue(config, 'config.debug'));
804
+ setFormField('config.support_escapes', getNestedValue(config, 'config.support_escapes'));
805
+
806
+ // Logging Settings
807
+ setFormField('log.level', getNestedValue(config, 'log.level'));
808
+ setFormField('log.format', getNestedValue(config, 'log.format'));
809
+ setFormField('log.format.json.fix_duplicate_message_fields', getNestedValue(config, 'log.format.json.fix_duplicate_message_fields'));
810
+ setFormField('path.logs', getNestedValue(config, 'path.logs'));
811
+
812
+ // Other Settings
813
+ setFormField('allow_superuser', getNestedValue(config, 'allow_superuser'));
814
+
815
+ // Handle path.plugins array
816
+ const pathPlugins = getNestedValue(config, 'path.plugins');
817
+ if (Array.isArray(pathPlugins)) {
818
+ setFormField('path.plugins', pathPlugins.join(', '));
819
+ }
820
+
821
+ // X-Pack Monitoring
822
+ setFormField('xpack.monitoring.enabled', getNestedValue(config, 'xpack.monitoring.enabled'));
823
+ setFormField('xpack.monitoring.collection.interval', getNestedValue(config, 'xpack.monitoring.collection.interval'));
824
+ setFormField('xpack.monitoring.elasticsearch.hosts',
825
+ Array.isArray(config?.xpack?.monitoring?.elasticsearch?.hosts)
826
+ ? config.xpack.monitoring.elasticsearch.hosts.join(', ')
827
+ : getNestedValue(config, 'xpack.monitoring.elasticsearch.hosts'));
828
+ setFormField('xpack.monitoring.elasticsearch.cloud_id', getNestedValue(config, 'xpack.monitoring.elasticsearch.cloud_id'));
829
+ setFormField('xpack.monitoring.elasticsearch.api_key', getNestedValue(config, 'xpack.monitoring.elasticsearch.api_key'));
830
+ setFormField('xpack.monitoring.elasticsearch.username', getNestedValue(config, 'xpack.monitoring.elasticsearch.username'));
831
+ setFormField('xpack.monitoring.elasticsearch.password', getNestedValue(config, 'xpack.monitoring.elasticsearch.password'));
832
+ setFormField('xpack.monitoring.elasticsearch.cloud_auth', getNestedValue(config, 'xpack.monitoring.elasticsearch.cloud_auth'));
833
+
834
+ // Handle proxy array
835
+ const monitoringProxy = getNestedValue(config, 'xpack.monitoring.elasticsearch.proxy');
836
+ if (Array.isArray(monitoringProxy)) {
837
+ setFormField('xpack.monitoring.elasticsearch.proxy', monitoringProxy.join(', '));
838
+ }
839
+
840
+ setFormField('xpack.monitoring.elasticsearch.ssl.certificate_authority', getNestedValue(config, 'xpack.monitoring.elasticsearch.ssl.certificate_authority'));
841
+ setFormField('xpack.monitoring.elasticsearch.ssl.ca_trusted_fingerprint', getNestedValue(config, 'xpack.monitoring.elasticsearch.ssl.ca_trusted_fingerprint'));
842
+ setFormField('xpack.monitoring.elasticsearch.ssl.truststore.path', getNestedValue(config, 'xpack.monitoring.elasticsearch.ssl.truststore.path'));
843
+ setFormField('xpack.monitoring.elasticsearch.ssl.truststore.password', getNestedValue(config, 'xpack.monitoring.elasticsearch.ssl.truststore.password'));
844
+ setFormField('xpack.monitoring.elasticsearch.ssl.keystore.path', getNestedValue(config, 'xpack.monitoring.elasticsearch.ssl.keystore.path'));
845
+ setFormField('xpack.monitoring.elasticsearch.ssl.keystore.password', getNestedValue(config, 'xpack.monitoring.elasticsearch.ssl.keystore.password'));
846
+ setFormField('xpack.monitoring.elasticsearch.ssl.certificate', getNestedValue(config, 'xpack.monitoring.elasticsearch.ssl.certificate'));
847
+ setFormField('xpack.monitoring.elasticsearch.ssl.key', getNestedValue(config, 'xpack.monitoring.elasticsearch.ssl.key'));
848
+ setFormField('xpack.monitoring.elasticsearch.ssl.verification_mode', getNestedValue(config, 'xpack.monitoring.elasticsearch.ssl.verification_mode'));
849
+
850
+ // Handle cipher_suites array
851
+ const monitoringCipherSuites = getNestedValue(config, 'xpack.monitoring.elasticsearch.ssl.cipher_suites');
852
+ if (Array.isArray(monitoringCipherSuites)) {
853
+ setFormField('xpack.monitoring.elasticsearch.ssl.cipher_suites', monitoringCipherSuites.join(', '));
854
+ }
855
+
856
+ setFormField('xpack.monitoring.elasticsearch.sniffing', getNestedValue(config, 'xpack.monitoring.elasticsearch.sniffing'));
857
+ setFormField('xpack.monitoring.allow_legacy_collection', getNestedValue(config, 'xpack.monitoring.allow_legacy_collection'));
858
+ setFormField('xpack.monitoring.collection.pipeline.details.enabled', getNestedValue(config, 'xpack.monitoring.collection.pipeline.details.enabled'));
859
+
860
+ // X-Pack Management
861
+ setFormField('xpack.management.enabled', getNestedValue(config, 'xpack.management.enabled'));
862
+ setFormField('xpack.management.logstash.poll_interval', getNestedValue(config, 'xpack.management.logstash.poll_interval'));
863
+
864
+ // Handle pipeline.id array
865
+ const pipelineIds = getNestedValue(config, 'xpack.management.pipeline.id');
866
+ if (Array.isArray(pipelineIds)) {
867
+ setFormField('xpack.management.pipeline.id', pipelineIds.join(', '));
868
+ }
869
+
870
+ setFormField('xpack.management.elasticsearch.hosts',
871
+ Array.isArray(config?.xpack?.management?.elasticsearch?.hosts)
872
+ ? config.xpack.management.elasticsearch.hosts.join(', ')
873
+ : getNestedValue(config, 'xpack.management.elasticsearch.hosts'));
874
+ setFormField('xpack.management.elasticsearch.cloud_id', getNestedValue(config, 'xpack.management.elasticsearch.cloud_id'));
875
+ setFormField('xpack.management.elasticsearch.api_key', getNestedValue(config, 'xpack.management.elasticsearch.api_key'));
876
+ setFormField('xpack.management.elasticsearch.username', getNestedValue(config, 'xpack.management.elasticsearch.username'));
877
+ setFormField('xpack.management.elasticsearch.password', getNestedValue(config, 'xpack.management.elasticsearch.password'));
878
+ setFormField('xpack.management.elasticsearch.cloud_auth', getNestedValue(config, 'xpack.management.elasticsearch.cloud_auth'));
879
+
880
+ // Handle proxy array
881
+ const managementProxy = getNestedValue(config, 'xpack.management.elasticsearch.proxy');
882
+ if (Array.isArray(managementProxy)) {
883
+ setFormField('xpack.management.elasticsearch.proxy', managementProxy.join(', '));
884
+ }
885
+
886
+ setFormField('xpack.management.elasticsearch.ssl.certificate_authority', getNestedValue(config, 'xpack.management.elasticsearch.ssl.certificate_authority'));
887
+ setFormField('xpack.management.elasticsearch.ssl.ca_trusted_fingerprint', getNestedValue(config, 'xpack.management.elasticsearch.ssl.ca_trusted_fingerprint'));
888
+ setFormField('xpack.management.elasticsearch.ssl.truststore.path', getNestedValue(config, 'xpack.management.elasticsearch.ssl.truststore.path'));
889
+ setFormField('xpack.management.elasticsearch.ssl.truststore.password', getNestedValue(config, 'xpack.management.elasticsearch.ssl.truststore.password'));
890
+ setFormField('xpack.management.elasticsearch.ssl.keystore.path', getNestedValue(config, 'xpack.management.elasticsearch.ssl.keystore.path'));
891
+ setFormField('xpack.management.elasticsearch.ssl.keystore.password', getNestedValue(config, 'xpack.management.elasticsearch.ssl.keystore.password'));
892
+ setFormField('xpack.management.elasticsearch.ssl.certificate', getNestedValue(config, 'xpack.management.elasticsearch.ssl.certificate'));
893
+ setFormField('xpack.management.elasticsearch.ssl.key', getNestedValue(config, 'xpack.management.elasticsearch.ssl.key'));
894
+
895
+ // Handle cipher_suites array
896
+ const managementCipherSuites = getNestedValue(config, 'xpack.management.elasticsearch.ssl.cipher_suites');
897
+ if (Array.isArray(managementCipherSuites)) {
898
+ setFormField('xpack.management.elasticsearch.ssl.cipher_suites', managementCipherSuites.join(', '));
899
+ }
900
+
901
+ setFormField('xpack.management.elasticsearch.ssl.verification_mode', getNestedValue(config, 'xpack.management.elasticsearch.ssl.verification_mode'));
902
+ setFormField('xpack.management.elasticsearch.sniffing', getNestedValue(config, 'xpack.management.elasticsearch.sniffing'));
903
+
904
+ // X-Pack GeoIP
905
+ setFormField('xpack.geoip.downloader.enabled', getNestedValue(config, 'xpack.geoip.downloader.enabled'));
906
+ setFormField('xpack.geoip.downloader.endpoint', getNestedValue(config, 'xpack.geoip.downloader.endpoint'));
907
+
908
+ // console.log('Successfully parsed YAML and populated form fields');
909
+
910
+ if (ymlContent === originalFileContents['logstash.yml']) {
911
+ originalFormYml = formToYml();
912
+ }
913
+ } catch (error) {
914
+ console.error('Error parsing YAML:', error);
915
+ console.error('YAML content that failed to parse:', ymlContent?.substring(0, 200));
916
+ // Don't show toast for parsing errors - they might be expected during initialization
917
+ // showToast('Error parsing YAML configuration: ' + error.message, 'error');
918
+ }
919
+ }
920
+
921
+ document.addEventListener('DOMContentLoaded', function() {
922
+ let editor = null;
923
+ let currentFile = 'logstash.yml';
924
+ let currentMode = 'form'; // 'form' or 'code'
925
+ let currentPolicy = null;
926
+ let customPolicies = []; // Store custom policy names
927
+
928
+ // Make currentFile globally accessible for save function
929
+ window.policyCurrentFile = currentFile;
930
+
931
+ // File contents will be loaded from the backend when a policy is selected
932
+ // Initialize empty fileContents object
933
+ const fileContents = {
934
+ 'logstash.yml': '',
935
+ 'jvm.options': '',
936
+ 'log4j2.properties': ''
937
+ };
938
+
939
+ // Make fileContents globally accessible for save function
940
+ window.policyFileContents = fileContents;
941
+
942
+ // Initialize CodeMirror
943
+ function initCodeMirror() {
944
+ const textarea = document.getElementById('codeEditor');
945
+ if (!textarea) return;
946
+
947
+ editor = CodeMirror.fromTextArea(textarea, {
948
+ lineNumbers: true,
949
+ mode: 'text/x-yaml',
950
+ indentUnit: 2,
951
+ tabSize: 2,
952
+ indentWithTabs: false,
953
+ lineWrapping: true,
954
+ matchBrackets: true,
955
+ autoCloseBrackets: true,
956
+ viewportMargin: Infinity,
957
+ extraKeys: {
958
+ "Tab": function(cm) {
959
+ cm.replaceSelection(" ", "end");
960
+ }
961
+ }
962
+ });
963
+
964
+ // Set CodeMirror to fill container
965
+ editor.setSize('100%', '100%');
966
+
967
+ // Make editor globally accessible
968
+ window.policyEditor = editor;
969
+
970
+ // Setup change detection after editor is ready
971
+ setTimeout(() => {
972
+ setupChangeDetection();
973
+ }, 500);
974
+
975
+ // Set initial content
976
+ editor.setValue(fileContents[currentFile]);
977
+
978
+ // Auto-refresh to ensure proper rendering
979
+ setTimeout(() => {
980
+ editor.refresh();
981
+ }, 100);
982
+ }
983
+
984
+ // Update documentation link based on file
985
+ function updateDocsLink(file) {
986
+ const bannerRow = document.getElementById('bannerRow');
987
+ const docsLink = document.getElementById('docsLink');
988
+ const requirementsTile = document.getElementById('requirementsTile');
989
+ const quickSetupRow = document.getElementById('quickSetupRow');
990
+ if (!docsLink || !bannerRow) return;
991
+
992
+ const tipTile = document.getElementById('tipTile');
993
+ const tipText = document.getElementById('tipText');
994
+
995
+ // Hide all optional tiles first, then selectively show
996
+ requirementsTile?.classList.add('hidden');
997
+ quickSetupRow?.classList.add('hidden');
998
+ tipTile?.classList.add('hidden');
999
+
1000
+ // No banner row for enrollment tokens or the Agents tab
1001
+ if (file === 'enrollment-tokens' || file === 'nodes') {
1002
+ bannerRow.classList.add('hidden');
1003
+ return;
1004
+ }
1005
+
1006
+ bannerRow.classList.remove('hidden');
1007
+
1008
+ if (file === 'logstash.yml') {
1009
+ // 6col guided setup | 3col requirements | 1col docs
1010
+ bannerRow.style.gridTemplateColumns = '6fr 3fr 1fr';
1011
+ quickSetupRow?.classList.remove('hidden');
1012
+ requirementsTile?.classList.remove('hidden');
1013
+ } else if (file === 'pipelines' || file === 'keystore') {
1014
+ // 1col tip | 1col docs
1015
+ bannerRow.style.gridTemplateColumns = '1fr 1fr';
1016
+ if (tipTile && tipText) {
1017
+ tipText.textContent = file === 'pipelines'
1018
+ ? 'Your pipelines are saved when you create or edit them.'
1019
+ : 'Your keystore keys are saved when you create or edit them.';
1020
+ tipTile.classList.remove('hidden');
1021
+ }
1022
+ } else {
1023
+ // jvm.options, log4j2.properties — docs only
1024
+ bannerRow.style.gridTemplateColumns = '1fr';
1025
+ }
1026
+
1027
+ const docsLinks = {
1028
+ 'logstash.yml': 'https://www.elastic.co/docs/reference/logstash/logstash-settings-file',
1029
+ 'jvm.options': 'https://www.elastic.co/docs/reference/logstash/jvm-settings',
1030
+ 'log4j2.properties': 'https://www.elastic.co/guide/en/logstash/8.19/logging.html#log4j2',
1031
+ 'pipelines': 'https://www.elastic.co/docs/reference/logstash/configuration-file-structure',
1032
+ 'keystore': 'https://www.elastic.co/docs/reference/logstash/keystore',
1033
+ };
1034
+ docsLink.href = docsLinks[file] || docsLinks['logstash.yml'];
1035
+ }
1036
+
1037
+ // File tab switching
1038
+ document.querySelectorAll('.file-tab').forEach(tab => {
1039
+ tab.addEventListener('click', function() {
1040
+ const file = this.dataset.file;
1041
+
1042
+ // Every branch below either returns or falls through to a different
1043
+ // view, so stop here and let the nodes branch restart it.
1044
+ stopPolicyNodesPolling();
1045
+
1046
+ // Update active tab
1047
+ document.querySelectorAll('.file-tab').forEach(t => {
1048
+ t.classList.remove('active');
1049
+ const span = t.querySelector('span');
1050
+ const svg = t.querySelector('svg');
1051
+ if (span) {
1052
+ span.classList.remove('text-white', 'font-semibold');
1053
+ span.classList.add('text-gray-500');
1054
+ }
1055
+ if (svg) {
1056
+ svg.classList.remove('opacity-60');
1057
+ svg.classList.add('opacity-40');
1058
+ }
1059
+ });
1060
+ this.classList.add('active');
1061
+ const span = this.querySelector('span');
1062
+ const svg = this.querySelector('svg');
1063
+ if (span) {
1064
+ span.classList.remove('text-gray-500');
1065
+ span.classList.add('text-white', 'font-semibold');
1066
+ }
1067
+ if (svg) {
1068
+ svg.classList.remove('opacity-40');
1069
+ svg.classList.add('opacity-60');
1070
+ }
1071
+
1072
+ // Update documentation link
1073
+ updateDocsLink(file);
1074
+
1075
+ // Store current file before switching
1076
+ const previousFile = currentFile;
1077
+
1078
+ // Save current content BEFORE switching
1079
+ if (previousFile && previousFile !== 'enrollment-tokens' && previousFile !== 'pipelines' && previousFile !== 'keystore') {
1080
+ if (currentMode === 'code' && editor) {
1081
+ // Save code mode content
1082
+ const currentContent = editor.getValue();
1083
+ if (currentContent !== undefined && currentContent !== null) {
1084
+ fileContents[previousFile] = currentContent;
1085
+ }
1086
+ } else if (currentMode === 'form' && previousFile === 'jvm.options') {
1087
+ applyJvmHeapToContent();
1088
+ fileContents['jvm.options'] = window.policyFileContents['jvm.options'] || '';
1089
+ } else if (currentMode === 'form' && previousFile === 'logstash.yml') {
1090
+ // Save form mode content by converting form to YAML
1091
+ try {
1092
+ const yamlContent = formToYml();
1093
+ if (yamlContent) {
1094
+ fileContents[previousFile] = yamlContent;
1095
+ }
1096
+ } catch (error) {
1097
+ console.error('Error saving form data:', error);
1098
+ }
1099
+ }
1100
+ }
1101
+
1102
+ // Now update to the new file
1103
+ currentFile = file;
1104
+
1105
+ // Update global currentFile reference
1106
+ window.policyCurrentFile = file;
1107
+
1108
+ // Persist active tab
1109
+ localStorage.setItem('agentPolicies_lastTab', file);
1110
+
1111
+ // Handle pipelines tab
1112
+ if (file === 'pipelines') {
1113
+ const modeToggleContainer = document.getElementById('modeToggleContainer');
1114
+ modeToggleContainer.classList.add('hidden');
1115
+
1116
+ // Hide notifications container
1117
+ const notificationsContainer = document.getElementById('notificationsContainer');
1118
+ if (notificationsContainer) {
1119
+ notificationsContainer.classList.add('hidden');
1120
+ }
1121
+
1122
+ // Hide other views
1123
+ const formModeEditor = document.getElementById('formModeEditor');
1124
+ const codeModeEditor = document.getElementById('codeModeEditor');
1125
+ const enrollmentTokensView = document.getElementById('enrollmentTokensView');
1126
+ const pipelinesView = document.getElementById('pipelinesView');
1127
+ const keystoreView = document.getElementById('keystoreView');
1128
+ const nodesView = document.getElementById('nodesView');
1129
+
1130
+ if (formModeEditor) formModeEditor.classList.add('hidden');
1131
+ if (codeModeEditor) codeModeEditor.classList.add('hidden');
1132
+ document.getElementById('jvmFormView')?.classList.add('hidden');
1133
+ if (enrollmentTokensView) enrollmentTokensView.classList.add('hidden');
1134
+ if (keystoreView) keystoreView.classList.add('hidden');
1135
+ if (nodesView) nodesView.classList.add('hidden');
1136
+ if (pipelinesView) {
1137
+ pipelinesView.classList.remove('hidden');
1138
+ // Load pipelines for current policy
1139
+ loadPolicyPipelines();
1140
+ }
1141
+ return;
1142
+ }
1143
+
1144
+ // Handle keystore tab
1145
+ if (file === 'keystore') {
1146
+ const modeToggleContainer = document.getElementById('modeToggleContainer');
1147
+ modeToggleContainer.classList.add('hidden');
1148
+
1149
+ // Hide notifications container
1150
+ const notificationsContainer = document.getElementById('notificationsContainer');
1151
+ if (notificationsContainer) {
1152
+ notificationsContainer.classList.add('hidden');
1153
+ }
1154
+
1155
+ // Hide other views
1156
+ const formModeEditor = document.getElementById('formModeEditor');
1157
+ const codeModeEditor = document.getElementById('codeModeEditor');
1158
+ const enrollmentTokensView = document.getElementById('enrollmentTokensView');
1159
+ const pipelinesView = document.getElementById('pipelinesView');
1160
+ const keystoreView = document.getElementById('keystoreView');
1161
+ const nodesView = document.getElementById('nodesView');
1162
+
1163
+ if (formModeEditor) formModeEditor.classList.add('hidden');
1164
+ if (codeModeEditor) codeModeEditor.classList.add('hidden');
1165
+ document.getElementById('jvmFormView')?.classList.add('hidden');
1166
+ if (enrollmentTokensView) enrollmentTokensView.classList.add('hidden');
1167
+ if (pipelinesView) pipelinesView.classList.add('hidden');
1168
+ if (nodesView) nodesView.classList.add('hidden');
1169
+ if (keystoreView) {
1170
+ keystoreView.classList.remove('hidden');
1171
+ // Load keystore for current policy
1172
+ loadPolicyKeystore();
1173
+ }
1174
+ return;
1175
+ }
1176
+
1177
+ // Handle nodes tab
1178
+ if (file === 'nodes') {
1179
+ const modeToggleContainer = document.getElementById('modeToggleContainer');
1180
+ modeToggleContainer.classList.add('hidden');
1181
+
1182
+ // Hide notifications container
1183
+ const notificationsContainer = document.getElementById('notificationsContainer');
1184
+ if (notificationsContainer) {
1185
+ notificationsContainer.classList.add('hidden');
1186
+ }
1187
+
1188
+ // Hide other views
1189
+ const formModeEditor = document.getElementById('formModeEditor');
1190
+ const codeModeEditor = document.getElementById('codeModeEditor');
1191
+ const enrollmentTokensView = document.getElementById('enrollmentTokensView');
1192
+ const pipelinesView = document.getElementById('pipelinesView');
1193
+ const keystoreView = document.getElementById('keystoreView');
1194
+ const nodesView = document.getElementById('nodesView');
1195
+
1196
+ if (formModeEditor) formModeEditor.classList.add('hidden');
1197
+ if (codeModeEditor) codeModeEditor.classList.add('hidden');
1198
+ document.getElementById('jvmFormView')?.classList.add('hidden');
1199
+ if (enrollmentTokensView) enrollmentTokensView.classList.add('hidden');
1200
+ if (pipelinesView) pipelinesView.classList.add('hidden');
1201
+ if (keystoreView) keystoreView.classList.add('hidden');
1202
+ if (nodesView) {
1203
+ nodesView.classList.remove('hidden');
1204
+ // Load nodes for current policy, then keep them current
1205
+ loadPolicyNodes();
1206
+ startPolicyNodesPolling();
1207
+ }
1208
+ return;
1209
+ }
1210
+
1211
+ // Handle enrollment tokens tab
1212
+ if (file === 'enrollment-tokens') {
1213
+ // Hide mode toggle for enrollment tokens
1214
+ const modeToggleContainer = document.getElementById('modeToggleContainer');
1215
+ modeToggleContainer.classList.add('hidden');
1216
+
1217
+ // Hide notifications container
1218
+ const notificationsContainer = document.getElementById('notificationsContainer');
1219
+ if (notificationsContainer) {
1220
+ notificationsContainer.classList.add('hidden');
1221
+ }
1222
+
1223
+ // Hide other views
1224
+ const formModeEditor = document.getElementById('formModeEditor');
1225
+ const codeModeEditor = document.getElementById('codeModeEditor');
1226
+ const enrollmentTokensView = document.getElementById('enrollmentTokensView');
1227
+ const pipelinesView = document.getElementById('pipelinesView');
1228
+ const keystoreView = document.getElementById('keystoreView');
1229
+ const nodesView = document.getElementById('nodesView');
1230
+
1231
+ if (formModeEditor) formModeEditor.classList.add('hidden');
1232
+ if (codeModeEditor) codeModeEditor.classList.add('hidden');
1233
+ document.getElementById('jvmFormView')?.classList.add('hidden');
1234
+ if (pipelinesView) pipelinesView.classList.add('hidden');
1235
+ if (keystoreView) keystoreView.classList.add('hidden');
1236
+ if (nodesView) nodesView.classList.add('hidden');
1237
+ if (enrollmentTokensView) {
1238
+ enrollmentTokensView.classList.remove('hidden');
1239
+ // Load enrollment tokens for current policy
1240
+ loadEnrollmentTokens();
1241
+ }
1242
+ return; // Exit early for enrollment tokens tab
1243
+ }
1244
+
1245
+ // Show/hide mode toggle based on file type
1246
+ const modeToggleContainer = document.getElementById('modeToggleContainer');
1247
+ const enrollmentTokensView = document.getElementById('enrollmentTokensView');
1248
+ const pipelinesView = document.getElementById('pipelinesView');
1249
+ const keystoreView = document.getElementById('keystoreView');
1250
+ const nodesView = document.getElementById('nodesView');
1251
+
1252
+ if (enrollmentTokensView) enrollmentTokensView.classList.add('hidden');
1253
+ if (pipelinesView) pipelinesView.classList.add('hidden');
1254
+ if (keystoreView) keystoreView.classList.add('hidden');
1255
+ if (nodesView) nodesView.classList.add('hidden');
1256
+
1257
+ if (file === 'logstash.yml') {
1258
+ modeToggleContainer.classList.remove('hidden');
1259
+ codeModeBtn.textContent = 'YML';
1260
+ switchToFormMode();
1261
+ if (editor) editor.setOption('mode', 'text/x-yaml');
1262
+ } else if (file === 'jvm.options') {
1263
+ modeToggleContainer.classList.remove('hidden');
1264
+ codeModeBtn.textContent = 'Text';
1265
+ switchToJvmFormMode();
1266
+ } else {
1267
+ modeToggleContainer.classList.add('hidden');
1268
+
1269
+ // Hide notifications container when switching away from logstash.yml
1270
+ const notificationsContainer = document.getElementById('notificationsContainer');
1271
+ if (notificationsContainer) notificationsContainer.classList.add('hidden');
1272
+
1273
+ switchToCodeMode();
1274
+
1275
+ if (editor) {
1276
+ let mode = 'text/plain';
1277
+ if (file.endsWith('.options') || file.endsWith('.properties')) {
1278
+ mode = 'text/x-simplecomment';
1279
+ }
1280
+ editor.setOption('mode', mode);
1281
+ const contentToLoad = fileContents[file] || '';
1282
+ editor.setValue(contentToLoad);
1283
+ editor.refresh();
1284
+ }
1285
+ }
1286
+ });
1287
+ });
1288
+
1289
+ // Mode toggle (Form/Code)
1290
+ const formModeBtn = document.getElementById('formModeBtn');
1291
+ const codeModeBtn = document.getElementById('codeModeBtn');
1292
+ const formModeEditor = document.getElementById('formModeEditor');
1293
+ const codeModeEditor = document.getElementById('codeModeEditor');
1294
+
1295
+ function switchToFormMode() {
1296
+ currentMode = 'form';
1297
+ formModeBtn.classList.add('active');
1298
+ codeModeBtn.classList.remove('active');
1299
+ formModeEditor.classList.remove('hidden');
1300
+ codeModeEditor.classList.add('hidden');
1301
+ document.getElementById('jvmFormView')?.classList.add('hidden');
1302
+
1303
+ const actualCurrentFile = window.policyCurrentFile || currentFile;
1304
+ if (actualCurrentFile === 'logstash.yml' && fileContents['logstash.yml']) {
1305
+ parseYmlToForm(fileContents['logstash.yml']);
1306
+ checkConfigNotifications();
1307
+ }
1308
+ }
1309
+
1310
+ function switchToJvmFormMode() {
1311
+ currentMode = 'form';
1312
+ formModeBtn.classList.add('active');
1313
+ codeModeBtn.classList.remove('active');
1314
+ formModeEditor.classList.add('hidden');
1315
+ codeModeEditor.classList.add('hidden');
1316
+ const jvmFormView = document.getElementById('jvmFormView');
1317
+ jvmFormView?.classList.remove('hidden');
1318
+ // Parse current Xms / Xmx values from jvm.options content
1319
+ const content = fileContents['jvm.options'] || '';
1320
+ const xmsMatch = content.match(/^-Xms(\d+)g/m);
1321
+ const xmxMatch = content.match(/^-Xmx(\d+)g/m);
1322
+ const xmsInput = document.getElementById('jvmXmsInput');
1323
+ const xmxInput = document.getElementById('jvmXmxInput');
1324
+ if (xmsInput) xmsInput.value = xmsMatch ? xmsMatch[1] : '';
1325
+ if (xmxInput) xmxInput.value = xmxMatch ? xmxMatch[1] : '';
1326
+ updateJvmHeapMismatchWarning();
1327
+ }
1328
+
1329
+ function switchToCodeMode() {
1330
+ currentMode = 'code';
1331
+ codeModeBtn.classList.add('active');
1332
+ formModeBtn.classList.remove('active');
1333
+ codeModeEditor.classList.remove('hidden');
1334
+ formModeEditor.classList.add('hidden');
1335
+ document.getElementById('jvmFormView')?.classList.add('hidden');
1336
+
1337
+ // Hide notifications container when switching to Code mode
1338
+ const notificationsContainer = document.getElementById('notificationsContainer');
1339
+ if (notificationsContainer) notificationsContainer.classList.add('hidden');
1340
+
1341
+ // If switching away from jvm form, write heap back to content first
1342
+ const actualCurrentFile = window.policyCurrentFile || currentFile;
1343
+ if (actualCurrentFile === 'jvm.options') {
1344
+ applyJvmHeapToContent();
1345
+ }
1346
+
1347
+ // Convert form to YAML if we're on logstash.yml tab
1348
+ if (currentFile === 'logstash.yml') {
1349
+ const yamlContent = formToYml();
1350
+ fileContents['logstash.yml'] = yamlContent;
1351
+ if (!editor) {
1352
+ initCodeMirror();
1353
+ editor.setValue(yamlContent);
1354
+ editor.refresh();
1355
+ } else {
1356
+ editor.setValue(yamlContent);
1357
+ editor.refresh();
1358
+ }
1359
+ } else {
1360
+ if (!editor) {
1361
+ initCodeMirror();
1362
+ } else {
1363
+ const contentToLoad = fileContents[currentFile] || '';
1364
+ editor.setValue(contentToLoad);
1365
+ editor.refresh();
1366
+ }
1367
+ }
1368
+ }
1369
+
1370
+ formModeBtn.addEventListener('click', () => {
1371
+ const activeFile = window.policyCurrentFile || currentFile;
1372
+ if (activeFile === 'jvm.options') {
1373
+ // Sync editor content back before switching to form (only when already on jvm.options tab)
1374
+ if (currentMode === 'code' && window.policyEditor) {
1375
+ const editorContent = window.policyEditor.getValue();
1376
+ fileContents['jvm.options'] = editorContent;
1377
+ window.policyFileContents['jvm.options'] = editorContent;
1378
+ }
1379
+ switchToJvmFormMode();
1380
+ } else {
1381
+ switchToFormMode();
1382
+ }
1383
+ });
1384
+ codeModeBtn.addEventListener('click', switchToCodeMode);
1385
+
1386
+ // Global Config toggle
1387
+ const globalConfigToggle = document.getElementById('globalConfigToggle');
1388
+ const globalConfigContent = document.getElementById('globalConfigContent');
1389
+ const globalConfigChevron = document.getElementById('globalConfigChevron');
1390
+
1391
+ globalConfigToggle.addEventListener('click', function() {
1392
+ globalConfigContent.classList.toggle('hidden');
1393
+ globalConfigChevron.classList.toggle('rotate-180');
1394
+ });
1395
+
1396
+ // Save button
1397
+ document.getElementById('saveBtn').addEventListener('click', savePolicyChanges);
1398
+
1399
+ // JVM heap inputs — update content live as user types
1400
+ const jvmInputHandler = () => {
1401
+ validateJvmHeapSettings();
1402
+ applyJvmHeapToContent();
1403
+ updateJvmHeapMismatchWarning();
1404
+ detectChanges();
1405
+ };
1406
+ document.getElementById('jvmXmsInput')?.addEventListener('input', jvmInputHandler);
1407
+ document.getElementById('jvmXmxInput')?.addEventListener('input', jvmInputHandler);
1408
+
1409
+ // Deploy button
1410
+ document.getElementById('deployBtn').addEventListener('click', function() {
1411
+ const policySelect = document.getElementById('policySelect');
1412
+ const selectedOption = policySelect.options[policySelect.selectedIndex];
1413
+ const policyId = selectedOption.dataset.policyId;
1414
+ const policyName = selectedOption.dataset.policyName || selectedOption.textContent;
1415
+
1416
+ if (!policyId) {
1417
+ showToast('No policy selected', 'error');
1418
+ return;
1419
+ }
1420
+
1421
+ // Show modal and load diff
1422
+ showDeployDiffModal();
1423
+ loadPolicyDiff(policyId, policyName);
1424
+ });
1425
+
1426
+ // Policy dropdown change handler
1427
+ const policySelect = document.getElementById('policySelect');
1428
+ const defaultPolicyIndicator = document.getElementById('defaultPolicyIndicator');
1429
+ const saveBtn = document.getElementById('saveBtn');
1430
+ const deployBtn = document.getElementById('deployBtn');
1431
+
1432
+ policySelect.addEventListener('change', async function() {
1433
+ const selectedValue = this.value;
1434
+
1435
+ // Persist selected policy to localStorage (skip add_new / unsaved draft)
1436
+ if (selectedValue !== 'add_new' && selectedValue !== DRAFT_POLICY_VALUE) {
1437
+ const selectedOpt = this.options[this.selectedIndex];
1438
+ const policyId = selectedOpt?.dataset.policyId;
1439
+ if (policyId) {
1440
+ localStorage.setItem('agentPolicies_lastPolicyId', policyId);
1441
+ }
1442
+ }
1443
+
1444
+ if (selectedValue === 'add_new') {
1445
+ const policyName = await ConfirmationModal.prompt(
1446
+ 'Enter a name for the new policy:',
1447
+ '',
1448
+ 'Add New Policy',
1449
+ 'e.g., Production Packaged'
1450
+ );
1451
+
1452
+ if (policyName && policyName.trim()) {
1453
+ const trimmedName = policyName.trim();
1454
+ const reservedNames = [
1455
+ 'default policy', 'packaged policy', 'managed policy', 'simulate policy', 'embedded policy',
1456
+ ];
1457
+ const existingNames = new Set([
1458
+ ...(window.customPolicies || []),
1459
+ ...customPolicies,
1460
+ ].map((n) => String(n).toLowerCase()));
1461
+ if (existingNames.has(trimmedName.toLowerCase()) || reservedNames.includes(trimmedName.toLowerCase())) {
1462
+ await ConfirmationModal.show(
1463
+ 'A policy with this name already exists. Please choose a different name.',
1464
+ 'Duplicate Policy Name',
1465
+ 'OK',
1466
+ null,
1467
+ true
1468
+ );
1469
+ this.value = currentPolicy;
1470
+ return;
1471
+ }
1472
+ enterDraftPolicy(trimmedName);
1473
+ } else {
1474
+ this.value = currentPolicy;
1475
+ }
1476
+ } else {
1477
+ discardDraftPolicyOption(this);
1478
+ currentPolicy = selectedValue;
1479
+ window.currentPolicy = currentPolicy;
1480
+ applyPolicyFieldEditability();
1481
+ if (isDraftPolicyOption(this.options[this.selectedIndex])) {
1482
+ return;
1483
+ }
1484
+ loadPolicyData(selectedValue);
1485
+ }
1486
+ });
1487
+
1488
+ // Function to update UI based on policy_type / is_system (from selected option)
1489
+ function updatePolicyUI(_legacyIsDefault) {
1490
+ applyPolicyFieldEditability();
1491
+ }
1492
+
1493
+ function setFieldDisabled(el, disabled) {
1494
+ if (!el) return;
1495
+ el.disabled = !!disabled;
1496
+ if (disabled) {
1497
+ el.classList.add('opacity-50', 'cursor-not-allowed');
1498
+ } else {
1499
+ el.classList.remove('opacity-50', 'cursor-not-allowed');
1500
+ }
1501
+ }
1502
+
1503
+ function applyPolicyFieldEditability() {
1504
+ const policySelect = document.getElementById('policySelect');
1505
+ const selectedOption = policySelect?.options[policySelect.selectedIndex];
1506
+ let policyType = (selectedOption?.dataset.policyType || 'PACKAGED').toUpperCase();
1507
+ if (policyType === 'DEFAULT') policyType = 'PACKAGED';
1508
+ const isSystem = selectedOption?.dataset.isSystem === 'true';
1509
+ const isEmbedded = policyType === 'EMBEDDED';
1510
+ const isSystemSimulate = isSystem && policyType === 'SIMULATE';
1511
+ const isSystemManaged = isSystem && policyType === 'MANAGED';
1512
+ const isSimulate = policyType === 'SIMULATE';
1513
+ const isManaged = policyType === 'MANAGED';
1514
+ const isSystemPathLocked = isSystemSimulate || isSystemManaged;
1515
+
1516
+ const deletePolicyBtn = document.getElementById('deletePolicyBtn');
1517
+ const clonePolicyBtn = document.getElementById('clonePolicyBtn');
1518
+ const banner = document.getElementById('policyLockBanner');
1519
+ const typeBadge = document.getElementById('policyTypeBadge');
1520
+ const systemBadge = document.getElementById('policySystemBadge');
1521
+ const simulateFields = document.getElementById('simulatePolicyFields');
1522
+
1523
+ const isDraft = selectedOption?.dataset.isDraft === 'true';
1524
+ if (typeBadge) {
1525
+ typeBadge.textContent = policyType;
1526
+ typeBadge.className = 'policy-role-badge ' + policyRoleClassName(policyType);
1527
+ }
1528
+ const typeSelect = document.getElementById('policyTypeSelect');
1529
+ if (typeSelect) typeSelect.value = policyType;
1530
+ syncPolicyTypeControl(isDraft);
1531
+ syncPolicyTypeInfo(policyType);
1532
+ if (systemBadge) {
1533
+ systemBadge.classList.toggle('hidden', !isSystem || isDraft);
1534
+ }
1535
+ if (simulateFields) {
1536
+ // VERSION source fields apply to Simulate and Managed multi-instance roles
1537
+ simulateFields.classList.toggle('hidden', !isSimulate && !isManaged && !isEmbedded);
1538
+ }
1539
+
1540
+ // Delete: system / draft / embedded cannot be deleted
1541
+ if (deletePolicyBtn) {
1542
+ if (isSystem || isEmbedded || isDraft) {
1543
+ deletePolicyBtn.classList.add('hidden');
1544
+ } else {
1545
+ deletePolicyBtn.classList.remove('hidden');
1546
+ }
1547
+ }
1548
+ // Clone: not for Embedded or unsaved draft
1549
+ if (clonePolicyBtn) {
1550
+ clonePolicyBtn.classList.toggle('hidden', isEmbedded || isDraft);
1551
+ }
1552
+
1553
+ // Path / binary fields
1554
+ const pathLocked = isEmbedded || isSystemPathLocked;
1555
+ setFieldDisabled(document.getElementById('settingsPath'), pathLocked);
1556
+ setFieldDisabled(document.getElementById('logsPath'), pathLocked);
1557
+ setFieldDisabled(document.getElementById('dataPath'), pathLocked);
1558
+ // binary path editable for simulate/managed (SYSTEM) and packaged
1559
+ setFieldDisabled(document.getElementById('binaryPath'), isEmbedded);
1560
+ setFieldDisabled(document.getElementById('keystoreEnvFile'), isEmbedded || isSystemPathLocked);
1561
+
1562
+ // Source fields
1563
+ setFieldDisabled(document.getElementById('logstashSource'), isEmbedded);
1564
+ setFieldDisabled(document.getElementById('logstashVersion'), isEmbedded);
1565
+ setFieldDisabled(document.getElementById('logstashDownloadDir'), isEmbedded);
1566
+ setFieldDisabled(document.getElementById('logstashViaUi'), isEmbedded);
1567
+ // Port defaults informational for system multi-instance (enroll formula wins)
1568
+ setFieldDisabled(document.getElementById('agentApiPort'), isEmbedded || isSystemPathLocked);
1569
+ setFieldDisabled(document.getElementById('logstashApiPort'), isEmbedded || isSystemPathLocked);
1570
+ const agentHint = document.getElementById('agentApiPortHint');
1571
+ const lsHint = document.getElementById('logstashApiPortHint');
1572
+ if (isManaged) {
1573
+ if (agentHint) agentHint.innerHTML = 'Enroll assigns <strong class="text-gray-400">9550+N</strong> per instance.';
1574
+ if (lsHint) lsHint.innerHTML = 'Enroll assigns <strong class="text-gray-400">9700+N</strong> per instance.';
1575
+ } else if (isSimulate) {
1576
+ if (agentHint) agentHint.innerHTML = 'Enroll assigns <strong class="text-gray-400">9500+N</strong> per instance.';
1577
+ if (lsHint) lsHint.innerHTML = 'Enroll assigns <strong class="text-gray-400">9560+N</strong> per instance.';
1578
+ } else if (isEmbedded) {
1579
+ if (agentHint) agentHint.innerHTML = 'Embedded agent API is fixed at <strong class="text-gray-400">9500</strong>.';
1580
+ if (lsHint) lsHint.innerHTML = 'Embedded Logstash API is fixed at <strong class="text-gray-400">9560</strong>.';
1581
+ } else {
1582
+ if (agentHint) agentHint.innerHTML = 'Packaged agent API uses this value as-is (<strong class="text-gray-400">9550</strong>).';
1583
+ if (lsHint) lsHint.innerHTML = 'Packaged Logstash API uses this value as-is (<strong class="text-gray-400">9600</strong>).';
1584
+ }
1585
+
1586
+ toggleVersionFieldsVisibility();
1587
+
1588
+ // Save / deploy / editor
1589
+ if (saveBtn) {
1590
+ if (isEmbedded) {
1591
+ saveBtn.disabled = true;
1592
+ saveBtn.classList.add('opacity-50', 'cursor-not-allowed');
1593
+ saveBtn.title = 'Embedded Policy cannot be modified';
1594
+ } else {
1595
+ saveBtn.disabled = false;
1596
+ saveBtn.classList.remove('opacity-50', 'cursor-not-allowed');
1597
+ saveBtn.title = '';
1598
+ }
1599
+ }
1600
+ if (deployBtn) {
1601
+ if (isEmbedded || isDraft) {
1602
+ deployBtn.disabled = true;
1603
+ deployBtn.classList.add('opacity-50', 'cursor-not-allowed');
1604
+ } else {
1605
+ deployBtn.disabled = false;
1606
+ deployBtn.classList.remove('opacity-50', 'cursor-not-allowed');
1607
+ }
1608
+ }
1609
+ if (typeof editor !== 'undefined' && editor) {
1610
+ editor.setOption('readOnly', isEmbedded);
1611
+ editor.getWrapperElement().style.opacity = isEmbedded ? '0.6' : '1';
1612
+ editor.getWrapperElement().style.cursor = isEmbedded ? 'not-allowed' : 'text';
1613
+ }
1614
+
1615
+ if (banner) {
1616
+ if (isEmbedded) {
1617
+ banner.classList.remove('hidden');
1618
+ banner.textContent = 'Embedded Policy is system-managed (Docker sim). Ports and paths are fixed; clone is not available.';
1619
+ } else if (isSystemSimulate) {
1620
+ banner.classList.remove('hidden');
1621
+ banner.textContent = 'System Simulate Policy: path scheme is fixed (simulate-N at enroll). You can edit JVM, logstash.yml, binary source/version, and binary path.';
1622
+ } else if (isSystemManaged) {
1623
+ banner.classList.remove('hidden');
1624
+ banner.textContent = 'System Managed Policy: path scheme is fixed (managed-N at enroll). Agent-owned isolated Logstash trees.';
1625
+ } else if (isSystem && (policyType === 'PACKAGED' || policyType === 'DEFAULT')) {
1626
+ banner.classList.remove('hidden');
1627
+ banner.textContent = 'System Packaged Policy: distro Logstash (system unit). Paths and config are editable; the policy itself cannot be deleted. Clone creates a Managed multi-instance policy.';
1628
+ } else if (isDraft) {
1629
+ banner.classList.remove('hidden');
1630
+ banner.textContent = 'Unsaved policy. Choose Packaged, Managed, or Simulate next to Policy Config, then Save.';
1631
+ } else if (!isSystem && isManaged) {
1632
+ banner.classList.remove('hidden');
1633
+ banner.textContent = 'Managed policy: each enrollment gets managed-N paths and ports.';
1634
+ } else {
1635
+ banner.classList.add('hidden');
1636
+ banner.textContent = '';
1637
+ }
1638
+ }
1639
+ }
1640
+
1641
+ function toggleVersionFieldsVisibility() {
1642
+ const source = document.getElementById('logstashSource')?.value || 'SYSTEM';
1643
+ const showVersion = source === 'VERSION';
1644
+ document.getElementById('logstashVersionWrap')?.classList.toggle('opacity-50', !showVersion);
1645
+ document.getElementById('logstashDownloadDirWrap')?.classList.toggle('opacity-50', !showVersion);
1646
+ const ver = document.getElementById('logstashVersion');
1647
+ const dl = document.getElementById('logstashDownloadDir');
1648
+ if (ver && !ver.disabled) ver.placeholder = showVersion ? 'e.g. 9.4.3' : '(only when source is VERSION)';
1649
+ if (dl && !dl.disabled) { /* keep value */ }
1650
+ const hint = document.getElementById('versionLifecycleHint');
1651
+ if (hint) {
1652
+ hint.classList.toggle('hidden', !showVersion);
1653
+ }
1654
+ // Only Managed and Simulate ever download a tarball. Packaged uses the OS
1655
+ // package and Embedded runs in-process, so the proxy is meaningless there.
1656
+ const ptype = document.getElementById('policyTypeSelect')?.value || '';
1657
+ const viaUiApplies = showVersion && (ptype === 'MANAGED' || ptype === 'SIMULATE');
1658
+ document.getElementById('logstashViaUiWrap')?.classList.toggle('hidden', !viaUiApplies);
1659
+ syncVersionBinaryPath();
1660
+ }
1661
+
1662
+ function setPolicyFieldValue(id, value) {
1663
+ const el = document.getElementById(id);
1664
+ if (el) el.value = value;
1665
+ }
1666
+
1667
+ function seedDraftFileContents(ptype) {
1668
+ const cache = window._policiesCache || [];
1669
+ const matchType = (p) => {
1670
+ let t = (p.policy_type || 'PACKAGED').toUpperCase();
1671
+ if (t === 'DEFAULT') t = 'PACKAGED';
1672
+ return t === ptype;
1673
+ };
1674
+ const match = cache.find((p) => matchType(p) && p.is_system) || cache.find(matchType);
1675
+ if (!window.policyFileContents) {
1676
+ window.policyFileContents = {
1677
+ 'logstash.yml': '',
1678
+ 'jvm.options': '',
1679
+ 'log4j2.properties': '',
1680
+ };
1681
+ }
1682
+ window.policyFileContents['logstash.yml'] = match?.logstash_yml || '';
1683
+ window.policyFileContents['jvm.options'] = match?.jvm_options || '';
1684
+ window.policyFileContents['log4j2.properties'] = match?.log4j2_properties || '';
1685
+ const yml = window.policyFileContents['logstash.yml'];
1686
+ if (yml && window.policyCurrentFile === 'logstash.yml') {
1687
+ const formMode = document.getElementById('formModeBtn')?.classList.contains('active');
1688
+ if (formMode) {
1689
+ parseYmlToForm(yml);
1690
+ }
1691
+ }
1692
+ if (window.policyEditor && window.policyCurrentFile) {
1693
+ window.policyEditor.setValue(window.policyFileContents[window.policyCurrentFile] || '');
1694
+ window.policyEditor.refresh();
1695
+ }
1696
+ storeOriginalContent();
1697
+ }
1698
+
1699
+ function applyDraftPolicyType(ptype) {
1700
+ ptype = (ptype || 'PACKAGED').toUpperCase();
1701
+ if (ptype === 'DEFAULT') ptype = 'PACKAGED';
1702
+ const select = document.getElementById('policySelect');
1703
+ const opt = select?.querySelector('option[data-is-draft="true"]');
1704
+ if (!opt) return;
1705
+ opt.dataset.policyType = ptype;
1706
+ opt.textContent = `${opt.dataset.policyName} (${ptype})`;
1707
+ const typeSelect = document.getElementById('policyTypeSelect');
1708
+ if (typeSelect) typeSelect.value = ptype;
1709
+
1710
+ if (ptype === 'MANAGED') {
1711
+ setPolicyFieldValue('settingsPath', '/opt/logstash-agent/managed-{instance_id}/settings');
1712
+ setPolicyFieldValue('logsPath', '/opt/logstash-agent/managed-{instance_id}/logs');
1713
+ setPolicyFieldValue('dataPath', '/opt/logstash-agent/managed-{instance_id}/data');
1714
+ setPolicyFieldValue('keystoreEnvFile', '/opt/logstash-agent/managed-{instance_id}/env');
1715
+ setPolicyFieldValue('binaryPath', '/usr/share/logstash/bin');
1716
+ setPolicyFieldValue('agentApiPort', '9550');
1717
+ setPolicyFieldValue('logstashApiPort', '9700');
1718
+ setPolicyFieldValue('logstashDownloadDir', '/opt/logstash-agent/logstash-versions');
1719
+ } else if (ptype === 'SIMULATE') {
1720
+ setPolicyFieldValue('settingsPath', '/opt/logstash-agent/simulate-{instance_id}/settings');
1721
+ setPolicyFieldValue('logsPath', '/opt/logstash-agent/simulate-{instance_id}/logs');
1722
+ setPolicyFieldValue('dataPath', '/opt/logstash-agent/simulate-{instance_id}/data');
1723
+ setPolicyFieldValue('keystoreEnvFile', '/opt/logstash-agent/simulate-{instance_id}/env');
1724
+ setPolicyFieldValue('binaryPath', '/usr/share/logstash/bin');
1725
+ setPolicyFieldValue('agentApiPort', '9500');
1726
+ setPolicyFieldValue('logstashApiPort', '9560');
1727
+ setPolicyFieldValue('logstashDownloadDir', '/opt/logstash-agent/logstash-versions');
1728
+ } else {
1729
+ setPolicyFieldValue('settingsPath', '/etc/logstash/');
1730
+ setPolicyFieldValue('logsPath', '/var/log/logstash');
1731
+ setPolicyFieldValue('dataPath', '');
1732
+ setPolicyFieldValue('keystoreEnvFile', '/etc/default/logstash');
1733
+ setPolicyFieldValue('binaryPath', '/usr/share/logstash/bin');
1734
+ setPolicyFieldValue('agentApiPort', '9550');
1735
+ setPolicyFieldValue('logstashApiPort', '9600');
1736
+ setPolicyFieldValue('logstashDownloadDir', '/opt/logstash-agent/logstash-versions');
1737
+ }
1738
+ if (document.getElementById('logstashSource')) {
1739
+ document.getElementById('logstashSource').value = 'SYSTEM';
1740
+ }
1741
+ seedDraftFileContents(ptype);
1742
+ window._policyDraftUnsaved = true;
1743
+ applyPolicyFieldEditability();
1744
+ if (typeof window.syncPolicySwitcherLabel === 'function') {
1745
+ window.syncPolicySwitcherLabel();
1746
+ }
1747
+ detectChanges();
1748
+ updateChangeIndicators();
1749
+ }
1750
+
1751
+ function discardDraftPolicyOption(select) {
1752
+ const target = select || document.getElementById('policySelect');
1753
+ const draft = target?.querySelector('option[data-is-draft="true"]');
1754
+ if (!draft) return;
1755
+ if (target.options[target.selectedIndex] === draft) return;
1756
+ draft.remove();
1757
+ window._policyDraftUnsaved = false;
1758
+ }
1759
+
1760
+ function closePolicyTypeInfo() {
1761
+ document.getElementById('policyTypeInfoPop')?.classList.add('hidden');
1762
+ document.getElementById('policyTypeInfoBtn')?.setAttribute('aria-expanded', 'false');
1763
+ const hover = document.getElementById('policyTypeInfoHover');
1764
+ if (hover && !hover.matches(':hover')) {
1765
+ hover.classList.add('hidden');
1766
+ }
1767
+ }
1768
+
1769
+ function currentPolicyTypeFromSelect() {
1770
+ const typeSelect = document.getElementById('policyTypeSelect');
1771
+ if (typeSelect && !typeSelect.disabled) {
1772
+ let t = (typeSelect.value || 'PACKAGED').toUpperCase();
1773
+ if (t === 'DEFAULT') t = 'PACKAGED';
1774
+ return t;
1775
+ }
1776
+ const select = document.getElementById('policySelect');
1777
+ const opt = select?.options[select.selectedIndex];
1778
+ let t = (opt?.dataset.policyType || 'PACKAGED').toUpperCase();
1779
+ if (t === 'DEFAULT') t = 'PACKAGED';
1780
+ return t;
1781
+ }
1782
+
1783
+ function syncPolicyTypeInfo(policyType) {
1784
+ const info = POLICY_TYPE_INFO[policyType] || POLICY_TYPE_INFO.PACKAGED;
1785
+ const hover = document.getElementById('policyTypeInfoHover');
1786
+ const body = document.getElementById('policyTypeInfoPopBody');
1787
+ const popBadge = document.getElementById('policyTypeInfoPopBadge');
1788
+ const infoBtn = document.getElementById('policyTypeInfoBtn');
1789
+ if (hover) hover.textContent = info.hover;
1790
+ if (body) body.textContent = info.body;
1791
+ if (popBadge) {
1792
+ popBadge.textContent = policyType;
1793
+ popBadge.className = 'policy-role-badge ' + policyRoleClassName(policyType);
1794
+ }
1795
+ if (infoBtn) infoBtn.removeAttribute('title');
1796
+ }
1797
+
1798
+ function syncPolicyTypeControl(isDraft) {
1799
+ const typeSelect = document.getElementById('policyTypeSelect');
1800
+ if (typeSelect) {
1801
+ typeSelect.disabled = !isDraft;
1802
+ if (isDraft) {
1803
+ typeSelect.classList.remove('opacity-50', 'cursor-not-allowed');
1804
+ } else {
1805
+ typeSelect.classList.add('opacity-50', 'cursor-not-allowed');
1806
+ }
1807
+ }
1808
+ syncPolicyTypeInfo(currentPolicyTypeFromSelect());
1809
+ }
1810
+
1811
+ function enterDraftPolicy(name) {
1812
+ const policySelect = document.getElementById('policySelect');
1813
+ const addNewOption = policySelect.querySelector('option[value="add_new"]');
1814
+ policySelect.querySelector('option[data-is-draft="true"]')?.remove();
1815
+
1816
+ const option = document.createElement('option');
1817
+ option.value = DRAFT_POLICY_VALUE;
1818
+ option.dataset.isDraft = 'true';
1819
+ option.dataset.policyName = name;
1820
+ option.dataset.policyType = 'PACKAGED';
1821
+ option.dataset.isSystem = 'false';
1822
+ option.textContent = `${name} (PACKAGED)`;
1823
+ policySelect.insertBefore(option, addNewOption);
1824
+ policySelect.value = DRAFT_POLICY_VALUE;
1825
+ currentPolicy = DRAFT_POLICY_VALUE;
1826
+ window.currentPolicy = currentPolicy;
1827
+
1828
+ document.getElementById('emptyState')?.classList.add('hidden');
1829
+ document.getElementById('mainContent')?.classList.remove('hidden');
1830
+
1831
+ const stats = {
1832
+ current_revision_number: 0,
1833
+ connection_count: 0,
1834
+ last_deployed_at: null,
1835
+ };
1836
+ updatePolicyStats(stats);
1837
+ updateDeployButtonIndicator(0);
1838
+
1839
+ window._policyDraftUnsaved = true;
1840
+ applyDraftPolicyType('PACKAGED');
1841
+ }
1842
+
1843
+ window.applyPolicyFieldEditability = applyPolicyFieldEditability;
1844
+ window.toggleVersionFieldsVisibility = toggleVersionFieldsVisibility;
1845
+ window.applyDraftPolicyType = applyDraftPolicyType;
1846
+ window.enterDraftPolicy = enterDraftPolicy;
1847
+
1848
+ document.getElementById('logstashSource')?.addEventListener('change', () => {
1849
+ toggleVersionFieldsVisibility();
1850
+ if (typeof detectChanges === 'function') detectChanges();
1851
+ });
1852
+ document.getElementById('logstashVersion')?.addEventListener('input', () => {
1853
+ syncVersionBinaryPath();
1854
+ if (typeof detectChanges === 'function') detectChanges();
1855
+ });
1856
+ document.getElementById('logstashVersion')?.addEventListener('change', () => {
1857
+ syncVersionBinaryPath();
1858
+ if (typeof detectChanges === 'function') detectChanges();
1859
+ });
1860
+ document.getElementById('logstashDownloadDir')?.addEventListener('input', () => {
1861
+ syncVersionBinaryPath();
1862
+ if (typeof detectChanges === 'function') detectChanges();
1863
+ });
1864
+ document.getElementById('logstashDownloadDir')?.addEventListener('change', () => {
1865
+ syncVersionBinaryPath();
1866
+ if (typeof detectChanges === 'function') detectChanges();
1867
+ });
1868
+
1869
+ // Load policies on page load, auto-selecting a policy if policy_id is in the URL
1870
+ const _urlParams = new URLSearchParams(window.location.search);
1871
+ const _urlPolicyId = _urlParams.get('policy_id');
1872
+ if (_urlPolicyId) {
1873
+ // URL param takes priority — also update localStorage so next visit restores this policy
1874
+ localStorage.setItem('agentPolicies_lastPolicyId', _urlPolicyId);
1875
+ }
1876
+ const _savedPolicyId = !_urlPolicyId ? localStorage.getItem('agentPolicies_lastPolicyId') : null;
1877
+
1878
+ // Capture saved tab NOW before loadPolicies triggers logstashTab.click() which would overwrite it
1879
+ window._pendingTabRestore = localStorage.getItem('agentPolicies_lastTab');
1880
+
1881
+ loadPolicies(null, _urlPolicyId ? parseInt(_urlPolicyId) : (_savedPolicyId ? parseInt(_savedPolicyId) : null));
1882
+
1883
+ // Add click handler for empty state Add Policy button
1884
+ const emptyStateAddPolicyBtn = document.getElementById('emptyStateAddPolicyBtn');
1885
+ if (emptyStateAddPolicyBtn) {
1886
+ emptyStateAddPolicyBtn.addEventListener('click', function() {
1887
+ // Trigger the same flow as selecting "+ Add Policy" from dropdown
1888
+ const policySelect = document.getElementById('policySelect');
1889
+ policySelect.value = 'add_new';
1890
+ policySelect.dispatchEvent(new Event('change'));
1891
+ });
1892
+ }
1893
+
1894
+ document.getElementById('policyTypeSelect')?.addEventListener('change', function () {
1895
+ const opt = document.getElementById('policySelect')?.options[
1896
+ document.getElementById('policySelect').selectedIndex
1897
+ ];
1898
+ if (!isDraftPolicyOption(opt)) return;
1899
+ applyDraftPolicyType(this.value);
1900
+ });
1901
+
1902
+ const infoBtn = document.getElementById('policyTypeInfoBtn');
1903
+ const infoHover = document.getElementById('policyTypeInfoHover');
1904
+ const infoPop = document.getElementById('policyTypeInfoPop');
1905
+ infoBtn?.addEventListener('mouseenter', () => {
1906
+ if (infoPop && !infoPop.classList.contains('hidden')) return;
1907
+ infoHover?.classList.remove('hidden');
1908
+ });
1909
+ infoBtn?.addEventListener('mouseleave', () => {
1910
+ infoHover?.classList.add('hidden');
1911
+ });
1912
+ infoBtn?.addEventListener('click', (e) => {
1913
+ e.stopPropagation();
1914
+ infoHover?.classList.add('hidden');
1915
+ const open = infoPop && !infoPop.classList.contains('hidden');
1916
+ infoPop?.classList.toggle('hidden', open);
1917
+ infoBtn.setAttribute('aria-expanded', open ? 'false' : 'true');
1918
+ });
1919
+ document.addEventListener('click', (e) => {
1920
+ const control = document.getElementById('policyTypeControl');
1921
+ if (control && !control.contains(e.target)) {
1922
+ closePolicyTypeInfo();
1923
+ }
1924
+ });
1925
+ document.addEventListener('keydown', (e) => {
1926
+ if (e.key === 'Escape') {
1927
+ closePolicyTypeInfo();
1928
+ }
1929
+ });
1930
+
1931
+ // Initialize in Form mode by default
1932
+ // (Form mode is already active by default in HTML)
1933
+ });
1934
+
1935
+ // Load specific policy data from the server
1936
+ async function loadPolicyData(policyValue) {
1937
+ try {
1938
+ const response = await fetch('/ConnectionManager/GetPolicies/', {
1939
+ method: 'GET',
1940
+ headers: {
1941
+ 'X-CSRFToken': getCsrfToken()
1942
+ }
1943
+ });
1944
+
1945
+ const data = await response.json();
1946
+
1947
+ if (data.success && data.policies) {
1948
+ // Find the policy by matching the value
1949
+ const policySelect = document.getElementById('policySelect');
1950
+ const selectedOption = policySelect.options[policySelect.selectedIndex];
1951
+ if (isDraftPolicyOption(selectedOption)) {
1952
+ return;
1953
+ }
1954
+ const policyName = selectedOption.dataset.policyName || selectedOption.textContent;
1955
+
1956
+ const policy = data.policies.find(p => p.name === policyName);
1957
+
1958
+ if (policy) {
1959
+ // Update form fields
1960
+ document.getElementById('settingsPath').value = policy.settings_path || '';
1961
+ document.getElementById('logsPath').value = policy.logs_path || '';
1962
+ document.getElementById('binaryPath').value = policy.binary_path || '/usr/share/logstash/bin';
1963
+ const dataPathEl = document.getElementById('dataPath');
1964
+ if (dataPathEl) dataPathEl.value = policy.data_path || '';
1965
+ const keystoreEnvEl = document.getElementById('keystoreEnvFile');
1966
+ if (keystoreEnvEl) keystoreEnvEl.value = policy.keystore_env_file || '/etc/default/logstash';
1967
+ const sourceEl = document.getElementById('logstashSource');
1968
+ if (sourceEl) sourceEl.value = policy.logstash_source || 'SYSTEM';
1969
+ const versionEl = document.getElementById('logstashVersion');
1970
+ if (versionEl) versionEl.value = policy.logstash_version || '';
1971
+ const downloadEl = document.getElementById('logstashDownloadDir');
1972
+ if (downloadEl) downloadEl.value = policy.logstash_download_dir || '/opt/logstash-agent/logstash-versions';
1973
+ const viaUiEl = document.getElementById('logstashViaUi');
1974
+ if (viaUiEl) viaUiEl.checked = !!policy.logstash_via_ui;
1975
+ syncVersionBinaryPath();
1976
+ const agentPortEl = document.getElementById('agentApiPort');
1977
+ if (agentPortEl) agentPortEl.value = policy.agent_api_port ?? 9500;
1978
+ const lsPortEl = document.getElementById('logstashApiPort');
1979
+ if (lsPortEl) lsPortEl.value = policy.logstash_api_port ?? 9560;
1980
+
1981
+ // Keep option dataset in sync for editability helpers
1982
+ if (selectedOption) {
1983
+ selectedOption.dataset.policyType = policy.policy_type || 'PACKAGED';
1984
+ selectedOption.dataset.isSystem = policy.is_system ? 'true' : 'false';
1985
+ }
1986
+ if (typeof applyPolicyFieldEditability === 'function') {
1987
+ applyPolicyFieldEditability();
1988
+ }
1989
+
1990
+ // Update file contents with fresh data from database
1991
+ window.policyFileContents['logstash.yml'] = policy.logstash_yml;
1992
+ window.policyFileContents['jvm.options'] = policy.jvm_options;
1993
+ window.policyFileContents['log4j2.properties'] = policy.log4j2_properties;
1994
+
1995
+ // Parse YAML and populate form fields ONLY for logstash.yml and ONLY if we're currently viewing it
1996
+ if (policy.logstash_yml && window.policyCurrentFile === 'logstash.yml') {
1997
+ const currentMode = document.getElementById('formModeBtn')?.classList.contains('active') ? 'form' : 'code';
1998
+ if (currentMode === 'form') {
1999
+ parseYmlToForm(policy.logstash_yml);
2000
+ }
2001
+ }
2002
+
2003
+ // Update editor if it's initialized and showing current file
2004
+ if (window.policyEditor && window.policyCurrentFile) {
2005
+ window.policyEditor.setValue(window.policyFileContents[window.policyCurrentFile] || '');
2006
+ window.policyEditor.refresh();
2007
+ }
2008
+
2009
+ // Store original content for change detection
2010
+ storeOriginalContent();
2011
+
2012
+ // Restore last active tab — use the value captured before page-load
2013
+ const _tabToRestore = window._pendingTabRestore || 'logstash.yml';
2014
+ window._pendingTabRestore = null; // consume it — only applies to initial load
2015
+ const _tabEl = document.querySelector(`.file-tab[data-file="${_tabToRestore}"]`);
2016
+ if (_tabEl) {
2017
+ _tabEl.click();
2018
+ } else {
2019
+ // Fallback: ensure banner row is initialized for logstash.yml
2020
+ updateDocsLink('logstash.yml');
2021
+ }
2022
+
2023
+ // Pulse the Default guide button if this policy has never been deployed
2024
+ const quickSetupRowEl = document.getElementById('quickSetupRow');
2025
+ if (quickSetupRowEl) {
2026
+ if (policy.current_revision_number === 0) {
2027
+ quickSetupRowEl.classList.add('guide-btn-highlight');
2028
+ } else {
2029
+ quickSetupRowEl.classList.remove('guide-btn-highlight');
2030
+ }
2031
+ }
2032
+
2033
+ // Update policy stats cards
2034
+ updatePolicyStats(policy);
2035
+
2036
+ // Refresh DB-backed tabs if one of them is currently active
2037
+ const activeTab = window.policyCurrentFile;
2038
+ if (activeTab === 'pipelines') {
2039
+ loadPolicyPipelines();
2040
+ } else if (activeTab === 'keystore') {
2041
+ loadPolicyKeystore();
2042
+ } else if (activeTab === 'enrollment-tokens') {
2043
+ loadEnrollmentTokens();
2044
+ }
2045
+
2046
+ // Check for configuration notifications after loading policy data
2047
+ // Use setTimeout to ensure DOM has updated
2048
+ setTimeout(() => {
2049
+ checkConfigNotifications();
2050
+ checkPathPermissionNotifications();
2051
+ }, 100);
2052
+ }
2053
+ }
2054
+ } catch (error) {
2055
+ console.error('Error loading policy data:', error);
2056
+ showToast('Failed to load policy data: ' + error.message, 'error');
2057
+ }
2058
+ }
2059
+
2060
+ async function updatePolicyStats(policy) {
2061
+ // Revision
2062
+ const revEl = document.getElementById('statRevision');
2063
+ if (revEl) {
2064
+ revEl.textContent = `#${policy.current_revision_number}`;
2065
+ }
2066
+
2067
+ // Managed instances
2068
+ const instEl = document.getElementById('statInstances');
2069
+ if (instEl) {
2070
+ instEl.textContent = policy.connection_count ?? '—';
2071
+ }
2072
+
2073
+ // Last deployed
2074
+ const deployedEl = document.getElementById('statLastDeployed');
2075
+ if (deployedEl) {
2076
+ if (policy.last_deployed_at) {
2077
+ const d = new Date(policy.last_deployed_at);
2078
+ deployedEl.textContent = d.toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' })
2079
+ + ' ' + d.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' });
2080
+ } else {
2081
+ deployedEl.textContent = 'Never';
2082
+ }
2083
+ }
2084
+
2085
+ // Undeployed changes — read from sectionsWithChanges after the diff modal loads
2086
+ // Set a placeholder now; it'll be updated once loadPolicyDiff populates sectionsWithChanges
2087
+ const pendingEl = document.getElementById('statPendingChanges');
2088
+ if (pendingEl) {
2089
+ pendingEl.textContent = '…';
2090
+ // Load the diff silently to populate sectionsWithChanges, then update the stat
2091
+ if (policy.id) {
2092
+ fetch(`/ConnectionManager/GetPolicyDiff/?policy_id=${policy.id}`, {
2093
+ headers: { 'X-CSRFToken': getCsrfToken() }
2094
+ }).then(r => r.json()).then(data => {
2095
+ if (!data.success) { pendingEl.textContent = '—'; return; }
2096
+ // Mirror the same logic as policy_deploy_modal.js renderSideBySideTextDiff / renderPipelinesDiff etc.
2097
+ const prev = data.previous;
2098
+ const curr = data.current;
2099
+ let count = 0;
2100
+ if ((prev.logstash_yml || '') !== (curr.logstash_yml || '')) count++;
2101
+ if ((prev.jvm_options || '') !== (curr.jvm_options || '')) count++;
2102
+ if ((prev.log4j2_properties || '') !== (curr.log4j2_properties || '')) count++;
2103
+ // Pipelines: compare JSON representation
2104
+ const prevPipes = JSON.stringify((prev.pipelines || []).map(p => p.name).sort());
2105
+ const currPipes = JSON.stringify((curr.pipelines || []).map(p => p.name).sort());
2106
+ if (prevPipes !== currPipes) count++;
2107
+ else {
2108
+ const prevLscl = JSON.stringify((prev.pipelines || []).sort((a,b) => a.name > b.name ? 1 : -1).map(p => p.lscl));
2109
+ const currLscl = JSON.stringify((curr.pipelines || []).sort((a,b) => a.name > b.name ? 1 : -1).map(p => p.lscl));
2110
+ if (prevLscl !== currLscl) count++;
2111
+ }
2112
+ // Keystore: compare key names
2113
+ const prevKeys = JSON.stringify((prev.keystore || []).map(k => k.key_name).sort());
2114
+ const currKeys = JSON.stringify((curr.keystore || []).map(k => k.key_name).sort());
2115
+ if (prevKeys !== currKeys) count++;
2116
+ // Keystore password: compare hash
2117
+ if ((prev.keystore_password_hash || '') !== (curr.keystore_password_hash || '')) count++;
2118
+ // Global settings
2119
+ if (prev.settings_path !== curr.settings_path || prev.logs_path !== curr.logs_path) count++;
2120
+
2121
+ // Update deploy button indicator (which also updates the stats strip)
2122
+ updateDeployButtonIndicator(count);
2123
+ }).catch(() => {
2124
+ pendingEl.textContent = '—';
2125
+ updateDeployButtonIndicator(0);
2126
+ });
2127
+ }
2128
+ }
2129
+ }
2130
+
2131
+ // Load all policies from the server
2132
+ // If newPolicyName is provided, select that policy after loading
2133
+ async function loadPolicies(newPolicyName = null, selectPolicyId = null) {
2134
+ try {
2135
+ const response = await fetch('/ConnectionManager/GetPolicies/', {
2136
+ method: 'GET',
2137
+ headers: {
2138
+ 'X-CSRFToken': getCsrfToken()
2139
+ }
2140
+ });
2141
+
2142
+ const data = await response.json();
2143
+
2144
+ if (data.success && data.policies) {
2145
+ const policySelect = document.getElementById('policySelect');
2146
+ const addNewOption = policySelect.querySelector('option[value="add_new"]');
2147
+ const emptyState = document.getElementById('emptyState');
2148
+ const mainContent = document.getElementById('mainContent');
2149
+ window._policiesCache = data.policies;
2150
+ window.customPolicies = [];
2151
+
2152
+ // Clear existing policies (keep only + Add Policy)
2153
+ const options = Array.from(policySelect.options);
2154
+ options.forEach(option => {
2155
+ if (option.value !== 'add_new') {
2156
+ option.remove();
2157
+ }
2158
+ });
2159
+
2160
+ // Check if we have any policies
2161
+ if (data.policies.length === 0) {
2162
+ // Show empty state, hide main content
2163
+ emptyState.classList.remove('hidden');
2164
+ mainContent.classList.add('hidden');
2165
+ return;
2166
+ }
2167
+
2168
+ // Hide empty state, show main content
2169
+ emptyState.classList.add('hidden');
2170
+ mainContent.classList.remove('hidden');
2171
+
2172
+ // Add policies from server (label includes role for clarity).
2173
+ // Embedded is docker/auto — never shown in this dropdown.
2174
+ data.policies.forEach(policy => {
2175
+ let ptype = (policy.policy_type || 'PACKAGED').toUpperCase();
2176
+ if (ptype === 'EMBEDDED') {
2177
+ return;
2178
+ }
2179
+ const option = document.createElement('option');
2180
+ option.value = policy.name.toLowerCase().replace(/\s+/g, '_');
2181
+ if (ptype === 'DEFAULT') ptype = 'PACKAGED';
2182
+ option.textContent = `${policy.name} (${ptype})`;
2183
+ option.dataset.policyName = policy.name;
2184
+ option.dataset.policyId = policy.id;
2185
+ option.dataset.policyType = ptype;
2186
+ option.dataset.isSystem = policy.is_system ? 'true' : 'false';
2187
+
2188
+ // Store policy data for later use
2189
+ option.dataset.settingsPath = policy.settings_path;
2190
+ option.dataset.logsPath = policy.logs_path;
2191
+ option.dataset.binaryPath = policy.binary_path;
2192
+ option.dataset.logstashYml = policy.logstash_yml;
2193
+ option.dataset.jvmOptions = policy.jvm_options;
2194
+ option.dataset.log4j2Properties = policy.log4j2_properties;
2195
+
2196
+ // Insert before "+ Add Policy" option
2197
+ policySelect.insertBefore(option, addNewOption);
2198
+
2199
+ window.customPolicies.push(policy.name);
2200
+ });
2201
+
2202
+ // Auto-select the appropriate policy
2203
+ if (data.policies.length > 0) {
2204
+ let policyToSelect;
2205
+
2206
+ // If a policy ID was provided (e.g. via URL param), select by ID first
2207
+ if (selectPolicyId) {
2208
+ policyToSelect = data.policies.find(p => p.id === selectPolicyId);
2209
+ }
2210
+
2211
+ // Then fall back to name match (e.g. after creating a new policy)
2212
+ if (!policyToSelect && newPolicyName) {
2213
+ policyToSelect = data.policies.find(p => p.name === newPolicyName);
2214
+ }
2215
+
2216
+ // Fall back to first policy if nothing matched
2217
+ if (!policyToSelect) {
2218
+ policyToSelect = data.policies[0];
2219
+ }
2220
+
2221
+ policySelect.value = policyToSelect.name.toLowerCase().replace(/\s+/g, '_');
2222
+ window.currentPolicy = policySelect.value;
2223
+
2224
+ // Trigger change event to load the policy data
2225
+ policySelect.dispatchEvent(new Event('change'));
2226
+ }
2227
+ }
2228
+ } catch (error) {
2229
+ console.error('Error loading policies:', error);
2230
+ showToast('Failed to load policies: ' + error.message, 'error');
2231
+ }
2232
+ }
2233
+
2234
+ // Get CSRF token from cookie
2235
+ function getCsrfToken() {
2236
+ const name = 'csrftoken';
2237
+ let cookieValue = null;
2238
+ if (document.cookie && document.cookie !== '') {
2239
+ const cookies = document.cookie.split(';');
2240
+ for (let i = 0; i < cookies.length; i++) {
2241
+ const cookie = cookies[i].trim();
2242
+ if (cookie.substring(0, name.length + 1) === (name + '=')) {
2243
+ cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
2244
+ break;
2245
+ }
2246
+ }
2247
+ }
2248
+ return cookieValue;
2249
+ }
2250
+
2251
+ // Save policy changes
2252
+ async function savePolicyChanges() {
2253
+ const policySelect = document.getElementById('policySelect');
2254
+ const selectedOption = policySelect.options[policySelect.selectedIndex];
2255
+ const policyName = selectedOption.dataset.policyName || selectedOption.textContent;
2256
+ const isDraft = isDraftPolicyOption(selectedOption);
2257
+
2258
+ // Get the current editor instance and save current content to fileContents
2259
+ const settingsPath = document.getElementById('settingsPath').value;
2260
+ const logsPath = document.getElementById('logsPath').value;
2261
+ const binaryPath = document.getElementById('binaryPath').value;
2262
+ const dataPath = document.getElementById('dataPath')?.value ?? '';
2263
+ const keystoreEnvFile = document.getElementById('keystoreEnvFile')?.value ?? '';
2264
+ const logstashSource = document.getElementById('logstashSource')?.value || 'SYSTEM';
2265
+ const logstashVersion = document.getElementById('logstashVersion')?.value || '';
2266
+ const logstashDownloadDir = document.getElementById('logstashDownloadDir')?.value || '';
2267
+ const logstashViaUi = !!document.getElementById('logstashViaUi')?.checked;
2268
+ const agentApiPort = parseInt(document.getElementById('agentApiPort')?.value, 10);
2269
+ const logstashApiPort = parseInt(document.getElementById('logstashApiPort')?.value, 10);
2270
+
2271
+ // Update fileContents with current editor/form state
2272
+ if (window.policyFileContents) {
2273
+ const currentFile = window.policyCurrentFile || 'logstash.yml';
2274
+ const isFormMode = document.getElementById('formModeBtn')?.classList.contains('active');
2275
+
2276
+ if (currentFile === 'logstash.yml') {
2277
+ if (isFormMode) {
2278
+ // Convert form data to YAML
2279
+ try {
2280
+ const yamlContent = formToYml();
2281
+ window.policyFileContents['logstash.yml'] = yamlContent;
2282
+ } catch (error) {
2283
+ console.error('Error converting form to YAML:', error);
2284
+ showToast('Error converting form to YAML: ' + error.message, 'error');
2285
+ return;
2286
+ }
2287
+ } else if (window.policyEditor) {
2288
+ window.policyFileContents['logstash.yml'] = window.policyEditor.getValue();
2289
+ }
2290
+ } else if (currentFile === 'jvm.options') {
2291
+ if (isFormMode) {
2292
+ // Form mode: write Xms/Xmx inputs into content — never touch the editor
2293
+ applyJvmHeapToContent();
2294
+ } else if (window.policyEditor) {
2295
+ // Text mode: editor holds the authoritative content
2296
+ window.policyFileContents['jvm.options'] = window.policyEditor.getValue();
2297
+ }
2298
+ } else if (window.policyEditor) {
2299
+ // All other file tabs are always in code/text mode
2300
+ window.policyFileContents[currentFile] = window.policyEditor.getValue();
2301
+ }
2302
+ }
2303
+
2304
+ const payload = {
2305
+ settings_path: settingsPath,
2306
+ logs_path: logsPath,
2307
+ binary_path: binaryPath,
2308
+ data_path: dataPath,
2309
+ keystore_env_file: keystoreEnvFile,
2310
+ logstash_source: logstashSource,
2311
+ logstash_version: logstashVersion,
2312
+ logstash_download_dir: logstashDownloadDir,
2313
+ logstash_via_ui: logstashViaUi,
2314
+ agent_api_port: Number.isFinite(agentApiPort) ? agentApiPort : undefined,
2315
+ logstash_api_port: Number.isFinite(logstashApiPort) ? logstashApiPort : undefined,
2316
+ logstash_yml: window.policyFileContents ? window.policyFileContents['logstash.yml'] : '',
2317
+ jvm_options: window.policyFileContents ? window.policyFileContents['jvm.options'] : '',
2318
+ log4j2_properties: window.policyFileContents ? window.policyFileContents['log4j2.properties'] : ''
2319
+ };
2320
+
2321
+ try {
2322
+ if (isDraft) {
2323
+ payload.name = policyName;
2324
+ payload.policy_type = (selectedOption.dataset.policyType || 'PACKAGED').toUpperCase();
2325
+ const response = await fetch('/ConnectionManager/AddPolicy/', {
2326
+ method: 'POST',
2327
+ headers: {
2328
+ 'Content-Type': 'application/json',
2329
+ 'X-CSRFToken': getCsrfToken()
2330
+ },
2331
+ body: JSON.stringify(payload)
2332
+ });
2333
+ const data = await response.json();
2334
+ if (data.success) {
2335
+ showToast(data.message, 'success');
2336
+ window._policyDraftUnsaved = false;
2337
+ await loadPolicies(policyName);
2338
+ } else {
2339
+ showToast(data.error || 'Failed to create policy', 'error');
2340
+ }
2341
+ return;
2342
+ }
2343
+
2344
+ payload.policy_name = policyName;
2345
+ const response = await fetch('/ConnectionManager/UpdatePolicy/', {
2346
+ method: 'POST',
2347
+ headers: {
2348
+ 'Content-Type': 'application/json',
2349
+ 'X-CSRFToken': getCsrfToken()
2350
+ },
2351
+ body: JSON.stringify(payload)
2352
+ });
2353
+
2354
+ const data = await response.json();
2355
+
2356
+ if (data.success) {
2357
+ showToast(data.message, 'success');
2358
+ // Reset change tracking after successful save
2359
+ resetChangeTracking();
2360
+ } else {
2361
+ showToast(data.error || 'Failed to update policy', 'error');
2362
+ }
2363
+ } catch (error) {
2364
+ console.error('Error saving policy:', error);
2365
+ showToast('Failed to save policy: ' + error.message, 'error');
2366
+ }
2367
+ }
2368
+
2369
+ // Delete current policy
2370
+ async function deleteCurrentPolicy() {
2371
+ const policySelect = document.getElementById('policySelect');
2372
+ const selectedOption = policySelect.options[policySelect.selectedIndex];
2373
+ const policyName = selectedOption.dataset.policyName || selectedOption.textContent;
2374
+
2375
+ const confirmed = await ConfirmationModal.show(
2376
+ `Are you sure you want to delete the policy "${policyName}"?\n\nThis action cannot be undone.`,
2377
+ 'Delete Policy',
2378
+ 'Delete',
2379
+ null,
2380
+ false
2381
+ );
2382
+
2383
+ if (!confirmed) {
2384
+ return;
2385
+ }
2386
+
2387
+ try {
2388
+ const response = await fetch('/ConnectionManager/DeletePolicy/', {
2389
+ method: 'POST',
2390
+ headers: {
2391
+ 'Content-Type': 'application/json',
2392
+ 'X-CSRFToken': getCsrfToken()
2393
+ },
2394
+ body: JSON.stringify({
2395
+ policy_name: policyName
2396
+ })
2397
+ });
2398
+
2399
+ const data = await response.json();
2400
+
2401
+ if (data.success) {
2402
+ showToast(data.message, 'success');
2403
+
2404
+ // Reload policies to refresh the UI
2405
+ // This will show empty state if no policies remain
2406
+ await loadPolicies();
2407
+ } else {
2408
+ showToast(data.error || 'Failed to delete policy', 'error');
2409
+ }
2410
+ } catch (error) {
2411
+ console.error('Error deleting policy:', error);
2412
+ showToast('Failed to delete policy: ' + error.message, 'error');
2413
+ }
2414
+ }
2415
+
2416
+ // Clone current policy
2417
+ async function cloneCurrentPolicy() {
2418
+ const policySelect = document.getElementById('policySelect');
2419
+ const selectedOption = policySelect.options[policySelect.selectedIndex];
2420
+ const policyName = selectedOption.dataset.policyName || selectedOption.textContent;
2421
+ const policyId = selectedOption.dataset.policyId;
2422
+
2423
+ if (!policyId) {
2424
+ showToast('No policy selected', 'error');
2425
+ return;
2426
+ }
2427
+
2428
+ // Prompt for new policy name
2429
+ const newPolicyName = await ConfirmationModal.prompt(
2430
+ `Enter a name for the cloned policy:`,
2431
+ `${policyName} (Copy)`,
2432
+ 'Clone Policy',
2433
+ 'New policy name'
2434
+ );
2435
+
2436
+ if (!newPolicyName) {
2437
+ return;
2438
+ }
2439
+
2440
+ try {
2441
+ const response = await fetch('/ConnectionManager/ClonePolicy/', {
2442
+ method: 'POST',
2443
+ headers: {
2444
+ 'Content-Type': 'application/json',
2445
+ 'X-CSRFToken': getCsrfToken()
2446
+ },
2447
+ body: JSON.stringify({
2448
+ source_policy_id: policyId,
2449
+ new_policy_name: newPolicyName
2450
+ })
2451
+ });
2452
+
2453
+ const data = await response.json();
2454
+
2455
+ if (data.success) {
2456
+ showToast(data.message, 'success');
2457
+
2458
+ // Reload policies and switch to the new policy
2459
+ await loadPolicies();
2460
+
2461
+ // Select the newly cloned policy
2462
+ const policySelect = document.getElementById('policySelect');
2463
+ const newOption = Array.from(policySelect.options).find(
2464
+ opt => opt.dataset.policyId == data.policy_id
2465
+ );
2466
+ if (newOption) {
2467
+ policySelect.value = newOption.value;
2468
+ await loadPolicyData();
2469
+ }
2470
+ } else {
2471
+ showToast(data.error || 'Failed to clone policy', 'error');
2472
+ }
2473
+ } catch (error) {
2474
+ console.error('Error cloning policy:', error);
2475
+ showToast('Failed to clone policy: ' + error.message, 'error');
2476
+ }
2477
+ }
2478
+
2479
+ // Load enrollment tokens for the current policy
2480
+ async function loadEnrollmentTokens() {
2481
+ const policySelect = document.getElementById('policySelect');
2482
+ const selectedOption = policySelect.options[policySelect.selectedIndex];
2483
+ const policyId = selectedOption.dataset.policyId;
2484
+
2485
+ if (!policyId) {
2486
+ console.error('No policy ID found');
2487
+ return;
2488
+ }
2489
+
2490
+ try {
2491
+ const response = await fetch(`/ConnectionManager/GetEnrollmentTokens/?policy_id=${policyId}`, {
2492
+ method: 'GET',
2493
+ headers: {
2494
+ 'X-CSRFToken': getCsrfToken()
2495
+ }
2496
+ });
2497
+
2498
+ const data = await response.json();
2499
+
2500
+ const tableBody = document.getElementById('enrollmentTokensTableBody');
2501
+
2502
+ if (data.success && data.tokens && data.tokens.length > 0) {
2503
+ // Clear existing rows
2504
+ tableBody.innerHTML = '';
2505
+
2506
+ // Add token rows
2507
+ data.tokens.forEach(token => {
2508
+ const row = document.createElement('tr');
2509
+ row.className = 'hover:bg-gray-700';
2510
+ // Prefer full install command (includes --logstash-ui-url from agent.ui_url)
2511
+ const copyPayload = token.enroll_command || token.encoded_token;
2512
+ const copyLabel = token.enroll_command ? 'Copy command' : 'Copy token';
2513
+ const copyEscaped = escapeHtml(copyPayload).replace(/'/g, "\\'");
2514
+ row.innerHTML = `
2515
+ <td class="px-4 py-3 text-sm text-gray-300">
2516
+ <span class="font-medium">${escapeHtml(token.name)}</span>
2517
+ </td>
2518
+ <td class="px-4 py-3 text-sm text-gray-300">
2519
+ <span class="font-mono text-xs break-all" title="Enrollment token (v2 may include CA fingerprint)">${escapeHtml(token.encoded_token)}</span>
2520
+ ${token.enroll_command ? `<div class="mt-1 text-xs text-gray-500 font-mono break-all">${escapeHtml(token.enroll_command)}</div>` : ''}
2521
+ </td>
2522
+ <td class="px-4 py-3 text-sm text-right">
2523
+ <div class="action-menu relative inline-block">
2524
+ <button class="action-menu-button p-1 hover:bg-gray-700 rounded" onclick="toggleEnrollmentTokenMenu(${token.id})">
2525
+ <svg class="h-5 w-5" fill="currentColor" viewBox="0 0 20 20">
2526
+ <path d="M10 6a2 2 0 110-4 2 2 0 010 4zM10 12a2 2 0 110-4 2 2 0 010 4zM10 18a2 2 0 110-4 2 2 0 010 4z" />
2527
+ </svg>
2528
+ </button>
2529
+ <div id="token-menu-${token.id}" class="action-menu-items hidden absolute right-0 bottom-full mb-1 z-50 w-40 bg-gray-800 rounded-md shadow-lg py-1" role="menu">
2530
+ <div class="px-1 py-1">
2531
+ <a href="#" onclick="event.preventDefault(); copyTokenToClipboard('${copyEscaped}'); toggleEnrollmentTokenMenu(${token.id}); return false;" class="group flex items-center px-4 py-2 text-sm text-blue-400 hover:bg-gray-700 rounded-md" role="menuitem">
2532
+ <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
2533
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
2534
+ </svg>
2535
+ ${copyLabel}
2536
+ </a>
2537
+ <a href="#" onclick="event.preventDefault(); deleteEnrollmentToken(${token.id}); return false;" class="group flex items-center px-4 py-2 text-sm text-red-400 hover:bg-gray-700 rounded-md" role="menuitem">
2538
+ <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
2539
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
2540
+ </svg>
2541
+ Delete
2542
+ </a>
2543
+ </div>
2544
+ </div>
2545
+ </div>
2546
+ </td>
2547
+ `;
2548
+ tableBody.appendChild(row);
2549
+ });
2550
+ } else {
2551
+ // Show empty state in table
2552
+ tableBody.innerHTML = `
2553
+ <tr>
2554
+ <td colspan="3" class="px-4 py-8 text-center text-gray-400">
2555
+ <div class="flex flex-col items-center gap-2">
2556
+ <svg class="w-12 h-12 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
2557
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z" />
2558
+ </svg>
2559
+ <p>No enrollment tokens found</p>
2560
+ <p class="text-sm">Tokens will be created automatically when you save this policy</p>
2561
+ </div>
2562
+ </td>
2563
+ </tr>
2564
+ `;
2565
+ }
2566
+ } catch (error) {
2567
+ console.error('Error loading enrollment tokens:', error);
2568
+ showToast('Failed to load enrollment tokens: ' + error.message, 'error');
2569
+ }
2570
+ }
2571
+
2572
+ // Toggle between encoded and raw token display
2573
+ function toggleTokenDisplay(tokenId, rawToken, encodedToken) {
2574
+ const displayElement = document.getElementById(`token-display-${tokenId}`);
2575
+ const toggleButton = document.getElementById(`toggle-btn-${tokenId}`);
2576
+
2577
+ if (displayElement.textContent === encodedToken) {
2578
+ // Show raw token
2579
+ displayElement.textContent = rawToken;
2580
+ toggleButton.textContent = 'Hide Raw';
2581
+ } else {
2582
+ // Show encoded token
2583
+ displayElement.textContent = encodedToken;
2584
+ toggleButton.textContent = 'Reveal Raw';
2585
+ }
2586
+ }
2587
+
2588
+ // Toggle enrollment token menu dropdown
2589
+ function toggleEnrollmentTokenMenu(tokenId) {
2590
+ const menu = document.getElementById(`token-menu-${tokenId}`);
2591
+
2592
+ // Close all other menus
2593
+ document.querySelectorAll('.action-menu-items').forEach(m => {
2594
+ if (m.id !== `token-menu-${tokenId}`) {
2595
+ m.classList.add('hidden');
2596
+ }
2597
+ });
2598
+
2599
+ // Toggle this menu
2600
+ menu.classList.toggle('hidden');
2601
+ }
2602
+
2603
+ // Delete enrollment token
2604
+ async function deleteEnrollmentToken(tokenId) {
2605
+ const confirmed = await ConfirmationModal.show(
2606
+ 'Are you sure you want to delete this enrollment token? This action cannot be undone.',
2607
+ 'Delete Enrollment Token',
2608
+ 'Delete',
2609
+ null,
2610
+ false
2611
+ );
2612
+
2613
+ if (!confirmed) {
2614
+ return;
2615
+ }
2616
+
2617
+ try {
2618
+ const response = await fetch('/ConnectionManager/DeleteEnrollmentToken/', {
2619
+ method: 'POST',
2620
+ headers: {
2621
+ 'Content-Type': 'application/json',
2622
+ 'X-CSRFToken': getCsrfToken()
2623
+ },
2624
+ body: JSON.stringify({
2625
+ token_id: tokenId
2626
+ })
2627
+ });
2628
+
2629
+ const data = await response.json();
2630
+
2631
+ if (data.success) {
2632
+ showToast(data.message || 'Enrollment token deleted successfully', 'success');
2633
+ // Reload enrollment tokens
2634
+ loadEnrollmentTokens();
2635
+ } else {
2636
+ showToast(data.error || 'Failed to delete enrollment token', 'error');
2637
+ }
2638
+ } catch (error) {
2639
+ console.error('Error deleting enrollment token:', error);
2640
+ showToast('Failed to delete enrollment token: ' + error.message, 'error');
2641
+ }
2642
+ }
2643
+
2644
+ // Copy token to clipboard
2645
+ function copyTokenToClipboard(token) {
2646
+ navigator.clipboard.writeText(token).then(() => {
2647
+ showToast('Token copied to clipboard', 'success');
2648
+ }).catch(err => {
2649
+ console.error('Failed to copy token:', err);
2650
+ showToast('Failed to copy token', 'error');
2651
+ });
2652
+ }
2653
+
2654
+ // Add new enrollment token
2655
+ async function addEnrollmentToken() {
2656
+ const policySelect = document.getElementById('policySelect');
2657
+ const selectedOption = policySelect.options[policySelect.selectedIndex];
2658
+ const policyId = selectedOption.dataset.policyId;
2659
+
2660
+ if (!policyId) {
2661
+ showToast('No policy selected', 'error');
2662
+ return;
2663
+ }
2664
+
2665
+ // Show prompt to name the enrollment token
2666
+ const tokenName = await ConfirmationModal.prompt(
2667
+ 'Enter a name for the enrollment token:',
2668
+ '',
2669
+ 'Add Enrollment Token',
2670
+ 'e.g., Production Token'
2671
+ );
2672
+
2673
+ if (!tokenName || !tokenName.trim()) {
2674
+ // User cancelled or entered empty name
2675
+ return;
2676
+ }
2677
+
2678
+ const trimmedName = tokenName.trim();
2679
+
2680
+ try {
2681
+ const response = await fetch('/ConnectionManager/AddEnrollmentToken/', {
2682
+ method: 'POST',
2683
+ headers: {
2684
+ 'Content-Type': 'application/json',
2685
+ 'X-CSRFToken': getCsrfToken()
2686
+ },
2687
+ body: JSON.stringify({
2688
+ policy_id: policyId,
2689
+ name: trimmedName
2690
+ })
2691
+ });
2692
+
2693
+ const data = await response.json();
2694
+
2695
+ if (data.success) {
2696
+ showToast(data.message || 'Enrollment token created successfully', 'success');
2697
+ // Reload enrollment tokens
2698
+ loadEnrollmentTokens();
2699
+ } else {
2700
+ showToast(data.error || 'Failed to create enrollment token', 'error');
2701
+ }
2702
+ } catch (error) {
2703
+ console.error('Error creating enrollment token:', error);
2704
+ showToast('Failed to create enrollment token: ' + error.message, 'error');
2705
+ }
2706
+ }
2707
+
2708
+ // Track modified form fields with subtle purple glow
2709
+ document.addEventListener('DOMContentLoaded', function() {
2710
+ const formInputs = document.querySelectorAll('#formModeEditor input, #formModeEditor select, #formModeEditor textarea');
2711
+
2712
+ formInputs.forEach(input => {
2713
+ // Store original value
2714
+ input.dataset.originalValue = input.value || '';
2715
+
2716
+ // Add event listener for changes
2717
+ input.addEventListener('input', function() {
2718
+ if (this.value !== this.dataset.originalValue && this.value !== '') {
2719
+ this.classList.add('field-modified');
2720
+ } else {
2721
+ this.classList.remove('field-modified');
2722
+ }
2723
+
2724
+ // Check notifications and detect changes
2725
+ checkConfigNotifications();
2726
+ detectChanges();
2727
+ });
2728
+
2729
+ // Also handle select changes
2730
+ input.addEventListener('change', function() {
2731
+ if (this.value !== this.dataset.originalValue && this.value !== '') {
2732
+ this.classList.add('field-modified');
2733
+ } else {
2734
+ this.classList.remove('field-modified');
2735
+ }
2736
+
2737
+ // Check for configuration notifications when fields change
2738
+ checkConfigNotifications();
2739
+ detectChanges();
2740
+ });
2741
+ });
2742
+
2743
+ // Add specific listeners to both logs path fields to ensure real-time detection
2744
+ const logsPathGlobalField = document.querySelector('[name="path.logs"]');
2745
+ const logsPathSettingField = document.getElementById('logsPath');
2746
+
2747
+ if (logsPathGlobalField) {
2748
+ logsPathGlobalField.addEventListener('input', () => {
2749
+ checkConfigNotifications();
2750
+ detectChanges();
2751
+ });
2752
+ logsPathGlobalField.addEventListener('change', () => {
2753
+ checkConfigNotifications();
2754
+ detectChanges();
2755
+ });
2756
+ // console.log('Added event listeners to global logs path field');
2757
+ }
2758
+
2759
+ if (logsPathSettingField) {
2760
+ logsPathSettingField.addEventListener('input', () => {
2761
+ checkConfigNotifications();
2762
+ detectChanges();
2763
+ checkPathPermissionNotifications();
2764
+ });
2765
+ logsPathSettingField.addEventListener('change', () => {
2766
+ checkConfigNotifications();
2767
+ detectChanges();
2768
+ checkPathPermissionNotifications();
2769
+ });
2770
+ // console.log('Added event listeners to config logs path field');
2771
+ }
2772
+
2773
+ // Policy Config fields are wired in setupChangeDetection() via POLICY_CONFIG_FIELD_IDS
2774
+
2775
+ // Initial check for notifications
2776
+ setTimeout(() => {
2777
+ checkConfigNotifications();
2778
+ checkPathPermissionNotifications();
2779
+ }, 500);
2780
+ });
2781
+
2782
+ // Close menus when clicking outside
2783
+ document.addEventListener('click', function(event) {
2784
+ if (!event.target.closest('.action-menu')) {
2785
+ document.querySelectorAll('.action-menu-items').forEach(menu => {
2786
+ menu.classList.add('hidden');
2787
+ });
2788
+ }
2789
+ });
2790
+
2791
+ // Update notification indicator in top bar
2792
+ function updateNotificationIndicator(notifications) {
2793
+ const indicator = document.getElementById('notificationIndicator');
2794
+ const badge = document.getElementById('notificationBadge');
2795
+ const tooltipContent = document.getElementById('notificationTooltipContent');
2796
+
2797
+ if (!indicator || !badge || !tooltipContent) return;
2798
+
2799
+ if (notifications.length > 0) {
2800
+ indicator.classList.remove('hidden');
2801
+
2802
+ const hasError = notifications.some(n => n.type === 'error');
2803
+ const severity = hasError ? 'error' : 'warning';
2804
+
2805
+ badge.className = `absolute top-0 right-0 block h-2 w-2 rounded-full ring-2 ring-gray-900 notification-badge-${severity} notification-glow-${severity}`;
2806
+
2807
+ tooltipContent.innerHTML = notifications.map(n => `
2808
+ <div class="flex items-start gap-2 p-2 bg-gray-700/50 rounded">
2809
+ <svg class="w-4 h-4 flex-shrink-0 mt-0.5 ${n.type === 'error' ? 'text-red-400' : 'text-yellow-400'}" fill="currentColor" viewBox="0 0 20 20">
2810
+ <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd" />
2811
+ </svg>
2812
+ <div>
2813
+ <div class="font-semibold ${n.type === 'error' ? 'text-red-300' : 'text-yellow-300'}">${n.title}</div>
2814
+ <div class="text-gray-400">${n.message}</div>
2815
+ </div>
2816
+ </div>
2817
+ `).join('');
2818
+ } else {
2819
+ indicator.classList.add('hidden');
2820
+ }
2821
+ }
2822
+
2823
+ // Notification indicator click handler
2824
+ document.addEventListener('DOMContentLoaded', function() {
2825
+ const notificationIndicatorBtn = document.getElementById('notificationIndicatorBtn');
2826
+ if (notificationIndicatorBtn) {
2827
+ notificationIndicatorBtn.addEventListener('click', function() {
2828
+ // Navigate to jvm.options when that's the only active notification source
2829
+ if (jvmNotifications.length > 0 && logstashNotifications.length === 0) {
2830
+ const jvmTab = document.querySelector('[data-file="jvm.options"]');
2831
+ if (jvmTab) {
2832
+ jvmTab.click();
2833
+ setTimeout(() => {
2834
+ const formModeBtn = document.getElementById('formModeBtn');
2835
+ if (formModeBtn && !formModeBtn.classList.contains('active')) {
2836
+ formModeBtn.click();
2837
+ }
2838
+ }, 100);
2839
+ }
2840
+ } else {
2841
+ const logstashTab = document.querySelector('[data-file="logstash.yml"]');
2842
+ if (logstashTab) {
2843
+ logstashTab.click();
2844
+ setTimeout(() => {
2845
+ const formModeBtn = document.getElementById('formModeBtn');
2846
+ if (formModeBtn && !formModeBtn.classList.contains('active')) {
2847
+ formModeBtn.click();
2848
+ }
2849
+ }, 100);
2850
+ }
2851
+ }
2852
+ });
2853
+ }
2854
+ });
2855
+
2856
+ // Load pipelines for the current policy
2857
+ async function loadPolicyPipelines() {
2858
+ if (!currentPolicy) {
2859
+ // console.log('No policy selected');
2860
+ return;
2861
+ }
2862
+
2863
+ const policySelect = document.getElementById('policySelect');
2864
+ const selectedOption = policySelect?.options[policySelect.selectedIndex];
2865
+ const policyId = selectedOption?.dataset.policyId;
2866
+
2867
+ if (!policyId) {
2868
+ // console.log('No policy ID found');
2869
+ return;
2870
+ }
2871
+
2872
+ try {
2873
+ // Fetch pipelines for this policy from the backend
2874
+ const response = await fetch(`/ConnectionManager/GetPolicyPipelines/?policy_id=${policyId}`, {
2875
+ method: 'GET',
2876
+ headers: {
2877
+ 'X-CSRFToken': getCsrfToken()
2878
+ }
2879
+ });
2880
+
2881
+ const data = await response.json();
2882
+
2883
+ if (data.success && data.pipelines) {
2884
+ // Initialize the pipeline list with the fetched data
2885
+ // Use 'policy' as the identifier since we're using default IDs in the template
2886
+ if (typeof initPipelineList === 'function') {
2887
+ initPipelineList('policy', data.pipelines);
2888
+ }
2889
+
2890
+ // Store the policy_id globally so the create modal can use it
2891
+ window.currentPolicyId = policyId;
2892
+ } else {
2893
+ // Show empty state
2894
+ const tableBody = document.getElementById('pipelineTableBody-policy');
2895
+ if (tableBody) {
2896
+ tableBody.innerHTML = `
2897
+ <tr>
2898
+ <td colspan="4" class="px-4 py-8 text-center text-gray-400">
2899
+ <div class="flex flex-col items-center gap-2">
2900
+ <svg class="w-12 h-12 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
2901
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4m0 5c0 2.21-3.582 4-8 4s-8-1.79-8-4" />
2902
+ </svg>
2903
+ <p>No pipelines found for this policy</p>
2904
+ </div>
2905
+ </td>
2906
+ </tr>
2907
+ `;
2908
+ }
2909
+ }
2910
+ } catch (error) {
2911
+ console.error('Error loading pipelines:', error);
2912
+ showToast('Failed to load pipelines: ' + error.message, 'error');
2913
+ }
2914
+ }
2915
+
2916
+ // Load keystore entries for the current policy
2917
+ async function loadPolicyKeystore() {
2918
+ const policySelect = document.getElementById('policySelect');
2919
+ const selectedOption = policySelect?.options[policySelect.selectedIndex];
2920
+ const policyId = selectedOption?.dataset.policyId;
2921
+
2922
+ if (!policyId) {
2923
+ // console.log('No policy selected');
2924
+ return;
2925
+ }
2926
+
2927
+ try {
2928
+ const response = await fetch(`/ConnectionManager/GetKeystoreEntries/?policy_id=${policyId}`, {
2929
+ method: 'GET',
2930
+ headers: {
2931
+ 'X-CSRFToken': getCsrfToken()
2932
+ }
2933
+ });
2934
+
2935
+ const data = await response.json();
2936
+ const tableBody = document.getElementById('keystoreTableBody');
2937
+
2938
+ if (data.success && tableBody) {
2939
+ // Toggle UI based on whether a keystore password is set
2940
+ const noPasswordBanner = document.getElementById('keystoreNoPasswordBanner');
2941
+ const passwordedControls = document.getElementById('keystorePasswordedControls');
2942
+ const tableContainer = document.getElementById('keystoreTableContainer');
2943
+
2944
+ if (data.has_keystore_password) {
2945
+ noPasswordBanner?.classList.add('hidden');
2946
+ passwordedControls?.classList.remove('hidden');
2947
+ tableContainer?.classList.remove('hidden');
2948
+ } else {
2949
+ noPasswordBanner?.classList.remove('hidden');
2950
+ passwordedControls?.classList.add('hidden');
2951
+ tableContainer?.classList.add('hidden');
2952
+ return;
2953
+ }
2954
+
2955
+ if (data.entries && data.entries.length > 0) {
2956
+ tableBody.innerHTML = data.entries.map(entry => `
2957
+ <tr class="hover:bg-gray-800/50">
2958
+ <td class="px-4 py-3 text-gray-300">${escapeHtml(entry.key_name)}</td>
2959
+ <td class="px-4 py-3 text-gray-400 font-mono text-sm">••••••••</td>
2960
+ <td class="px-4 py-3 text-gray-400 text-xs">${new Date(entry.last_updated).toLocaleString()}</td>
2961
+ <td class="text-right px-4 py-3">
2962
+ <div class="action-menu relative inline-block">
2963
+ <button class="action-menu-button p-1 hover:bg-gray-700 rounded">
2964
+ <svg class="h-5 w-5" fill="currentColor" viewBox="0 0 20 20">
2965
+ <path d="M10 6a2 2 0 110-4 2 2 0 010 4zM10 12a2 2 0 110-4 2 2 0 010 4zM10 18a2 2 0 110-4 2 2 0 010 4z" />
2966
+ </svg>
2967
+ </button>
2968
+ <div class="action-menu-items hidden fixed z-50 w-32 bg-gray-800 rounded-md shadow-lg py-1" role="menu">
2969
+ <div class="px-1 py-1">
2970
+ <button onclick="editKeystoreEntry(${entry.id}, '${escapeHtml(entry.key_name)}')" class="w-full group flex items-center px-4 py-2 text-sm text-blue-400 hover:bg-gray-700 rounded-md" role="menuitem" type="button">
2971
+ <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
2972
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
2973
+ </svg>
2974
+ Edit
2975
+ </button>
2976
+ <button onclick="deleteKeystoreEntry(${entry.id}, '${escapeHtml(entry.key_name)}')" class="w-full group flex items-center px-4 py-2 text-sm text-red-400 hover:bg-gray-700 rounded-md" role="menuitem" type="button">
2977
+ <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
2978
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
2979
+ </svg>
2980
+ Delete
2981
+ </button>
2982
+ </div>
2983
+ </div>
2984
+ </div>
2985
+ </td>
2986
+ </tr>
2987
+ `).join('');
2988
+
2989
+ // Setup action menu functionality after rendering
2990
+ setupKeystoreActionMenus();
2991
+ } else {
2992
+ tableBody.innerHTML = `
2993
+ <tr>
2994
+ <td colspan="4" class="px-4 py-8 text-center text-gray-400">
2995
+ <div class="flex flex-col items-center gap-2">
2996
+ <svg class="w-12 h-12 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
2997
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z" />
2998
+ </svg>
2999
+ <p>No keystore entries found</p>
3000
+ </div>
3001
+ </td>
3002
+ </tr>
3003
+ `;
3004
+ }
3005
+ }
3006
+ } catch (error) {
3007
+ console.error('Error loading keystore:', error);
3008
+ showToast('Failed to load keystore entries', 'error');
3009
+ }
3010
+ }
3011
+
3012
+ async function showSetKeystorePasswordModal() {
3013
+ const policySelect = document.getElementById('policySelect');
3014
+ const selectedOption = policySelect?.options[policySelect.selectedIndex];
3015
+ const policyId = selectedOption?.dataset.policyId;
3016
+
3017
+ if (!policyId) {
3018
+ showToast('Please select a policy first', 'error');
3019
+ return;
3020
+ }
3021
+
3022
+ const password = await ConfirmationModal.prompt(
3023
+ 'Please input a keystore password.',
3024
+ '',
3025
+ 'Set Keystore Password',
3026
+ 'Enter password...',
3027
+ true
3028
+ );
3029
+
3030
+ if (!password) return;
3031
+
3032
+ try {
3033
+ const response = await fetch('/ConnectionManager/SetKeystorePassword/', {
3034
+ method: 'POST',
3035
+ headers: {
3036
+ 'Content-Type': 'application/json',
3037
+ 'X-CSRFToken': getCsrfToken()
3038
+ },
3039
+ body: JSON.stringify({ policy_id: policyId, password: password })
3040
+ });
3041
+
3042
+ const data = await response.json();
3043
+
3044
+ if (data.success) {
3045
+ showToast(data.message, 'success');
3046
+ loadPolicyKeystore();
3047
+ } else {
3048
+ showToast(data.error || 'Failed to set keystore password', 'error');
3049
+ }
3050
+ } catch (error) {
3051
+ console.error('Error setting keystore password:', error);
3052
+ showToast('Failed to set keystore password', 'error');
3053
+ }
3054
+ }
3055
+
3056
+ async function showChangeKeystorePasswordModal() {
3057
+ const policySelect = document.getElementById('policySelect');
3058
+ const selectedOption = policySelect?.options[policySelect.selectedIndex];
3059
+ const policyId = selectedOption?.dataset.policyId;
3060
+
3061
+ if (!policyId) {
3062
+ showToast('Please select a policy first', 'error');
3063
+ return;
3064
+ }
3065
+
3066
+ const confirmed = await ConfirmationModal.show(
3067
+ 'WARNING: If you change the keystore password, the keystore will be destroyed and recreated. All existing keystore entries will be re-applied automatically.',
3068
+ 'Change Keystore Password',
3069
+ 'Continue'
3070
+ );
3071
+
3072
+ if (!confirmed) return;
3073
+
3074
+ const password = await ConfirmationModal.prompt(
3075
+ 'Enter new keystore password:',
3076
+ '',
3077
+ 'New Keystore Password',
3078
+ 'Enter new password...',
3079
+ true
3080
+ );
3081
+
3082
+ if (!password) return;
3083
+
3084
+ try {
3085
+ const response = await fetch('/ConnectionManager/SetKeystorePassword/', {
3086
+ method: 'POST',
3087
+ headers: {
3088
+ 'Content-Type': 'application/json',
3089
+ 'X-CSRFToken': getCsrfToken()
3090
+ },
3091
+ body: JSON.stringify({ policy_id: policyId, password: password })
3092
+ });
3093
+
3094
+ const data = await response.json();
3095
+
3096
+ if (data.success) {
3097
+ showToast(data.message, 'success');
3098
+ loadPolicyKeystore();
3099
+ } else {
3100
+ showToast(data.error || 'Failed to change keystore password', 'error');
3101
+ }
3102
+ } catch (error) {
3103
+ console.error('Error changing keystore password:', error);
3104
+ showToast('Failed to change keystore password', 'error');
3105
+ }
3106
+ }
3107
+
3108
+ // Keystore CRUD operations
3109
+ async function showCreateKeystoreModal() {
3110
+ const policySelect = document.getElementById('policySelect');
3111
+ const selectedOption = policySelect?.options[policySelect.selectedIndex];
3112
+ const policyId = selectedOption?.dataset.policyId;
3113
+
3114
+ if (!policyId) {
3115
+ showToast('Please select a policy first', 'error');
3116
+ return;
3117
+ }
3118
+
3119
+ const result = await KeystoreModal.showCreate();
3120
+ if (!result) return;
3121
+
3122
+ try {
3123
+ const response = await fetch('/ConnectionManager/CreateKeystoreEntry/', {
3124
+ method: 'POST',
3125
+ headers: {
3126
+ 'Content-Type': 'application/json',
3127
+ 'X-CSRFToken': getCsrfToken()
3128
+ },
3129
+ body: JSON.stringify({
3130
+ policy_id: policyId,
3131
+ key_name: result.keyName,
3132
+ key_value: result.keyValue
3133
+ })
3134
+ });
3135
+
3136
+ const data = await response.json();
3137
+
3138
+ if (data.success) {
3139
+ showToast(data.message, 'success');
3140
+ loadPolicyKeystore(); // Reload the table
3141
+ } else {
3142
+ showToast(data.error || 'Failed to create keystore entry', 'error');
3143
+ }
3144
+ } catch (error) {
3145
+ console.error('Error creating keystore entry:', error);
3146
+ showToast('Failed to create keystore entry', 'error');
3147
+ }
3148
+ }
3149
+
3150
+ async function editKeystoreEntry(entryId, keyName) {
3151
+ // Close any open action menus
3152
+ document.querySelectorAll('.action-menu-items').forEach(menu => {
3153
+ menu.classList.add('hidden');
3154
+ });
3155
+
3156
+ const newValue = await KeystoreModal.showEdit(keyName);
3157
+ if (!newValue) return;
3158
+
3159
+ try {
3160
+ const response = await fetch('/ConnectionManager/UpdateKeystoreEntry/', {
3161
+ method: 'POST',
3162
+ headers: {
3163
+ 'Content-Type': 'application/json',
3164
+ 'X-CSRFToken': getCsrfToken()
3165
+ },
3166
+ body: JSON.stringify({
3167
+ entry_id: entryId,
3168
+ key_value: newValue
3169
+ })
3170
+ });
3171
+
3172
+ const data = await response.json();
3173
+
3174
+ if (data.success) {
3175
+ showToast(data.message, 'success');
3176
+ loadPolicyKeystore(); // Reload the table
3177
+ } else {
3178
+ showToast(data.error || 'Failed to update keystore entry', 'error');
3179
+ }
3180
+ } catch (error) {
3181
+ console.error('Error updating keystore entry:', error);
3182
+ showToast('Failed to update keystore entry', 'error');
3183
+ }
3184
+ }
3185
+
3186
+ async function deleteKeystoreEntry(entryId, keyName) {
3187
+ // Close any open action menus
3188
+ document.querySelectorAll('.action-menu-items').forEach(menu => {
3189
+ menu.classList.add('hidden');
3190
+ });
3191
+
3192
+ const confirmed = await ConfirmationModal.show(
3193
+ `Are you sure you want to delete the keystore entry "${keyName}"?\n\nThis action cannot be undone.`,
3194
+ 'Delete Keystore Entry',
3195
+ 'Delete',
3196
+ null,
3197
+ false
3198
+ );
3199
+
3200
+ if (!confirmed) return;
3201
+
3202
+ try {
3203
+ const response = await fetch('/ConnectionManager/DeleteKeystoreEntry/', {
3204
+ method: 'POST',
3205
+ headers: {
3206
+ 'Content-Type': 'application/json',
3207
+ 'X-CSRFToken': getCsrfToken()
3208
+ },
3209
+ body: JSON.stringify({
3210
+ entry_id: entryId
3211
+ })
3212
+ });
3213
+
3214
+ const data = await response.json();
3215
+
3216
+ if (data.success) {
3217
+ showToast(data.message, 'success');
3218
+ loadPolicyKeystore(); // Reload the table
3219
+ } else {
3220
+ showToast(data.error || 'Failed to delete keystore entry', 'error');
3221
+ }
3222
+ } catch (error) {
3223
+ console.error('Error deleting keystore entry:', error);
3224
+ showToast('Failed to delete keystore entry', 'error');
3225
+ }
3226
+ }
3227
+
3228
+ function previousKeystorePage() {
3229
+ // console.log('Previous keystore page');
3230
+ }
3231
+
3232
+ function nextKeystorePage() {
3233
+ // console.log('Next keystore page');
3234
+ }
3235
+
3236
+ // Handle action menu (3-dot icon) functionality for keystore table
3237
+ document.addEventListener('click', function(e) {
3238
+ // Close all open action menus when clicking anywhere
3239
+ if (!e.target.closest('.action-menu')) {
3240
+ document.querySelectorAll('.action-menu-items').forEach(menu => {
3241
+ menu.classList.add('hidden');
3242
+ });
3243
+ }
3244
+ });
3245
+
3246
+ // Setup action menu toggle functionality
3247
+ function setupKeystoreActionMenus() {
3248
+ document.querySelectorAll('.action-menu-button').forEach(button => {
3249
+ // Remove existing listeners to avoid duplicates
3250
+ const newButton = button.cloneNode(true);
3251
+ button.parentNode.replaceChild(newButton, button);
3252
+
3253
+ newButton.addEventListener('click', function(e) {
3254
+ e.stopPropagation();
3255
+ const menu = this.nextElementSibling;
3256
+ const isHidden = menu.classList.contains('hidden');
3257
+
3258
+ // Close all other open menus
3259
+ document.querySelectorAll('.action-menu-items').forEach(m => {
3260
+ if (m !== menu) m.classList.add('hidden');
3261
+ });
3262
+
3263
+ // Position the menu at the cursor
3264
+ if (isHidden) {
3265
+ const rect = this.getBoundingClientRect();
3266
+ menu.style.left = `${e.clientX}px`;
3267
+ menu.style.top = `${e.clientY}px`;
3268
+ }
3269
+
3270
+ // Toggle current menu
3271
+ menu.classList.toggle('hidden', !isHidden);
3272
+ });
3273
+ });
3274
+ }
3275
+
3276
+ // Close menu when scrolling
3277
+ window.addEventListener('scroll', function() {
3278
+ document.querySelectorAll('.action-menu-items').forEach(menu => {
3279
+ menu.classList.add('hidden');
3280
+ });
3281
+ }, true);
3282
+
3283
+ // Policy Config fields that participate in the purple unsaved-change tracker
3284
+ const POLICY_CONFIG_FIELD_IDS = [
3285
+ 'settingsPath',
3286
+ 'logsPath',
3287
+ 'binaryPath',
3288
+ 'dataPath',
3289
+ 'keystoreEnvFile',
3290
+ 'logstashSource',
3291
+ 'logstashVersion',
3292
+ 'logstashDownloadDir',
3293
+ 'logstashViaUi',
3294
+ 'agentApiPort',
3295
+ 'logstashApiPort',
3296
+ ];
3297
+
3298
+ // A checkbox reports value "on" whether or not it is checked, so reading .value
3299
+ // would make logstashViaUi permanently invisible to the change tracker.
3300
+ function policyFieldValue(el) {
3301
+ if (!el) return '';
3302
+ return el.type === 'checkbox' ? String(el.checked) : (el.value ?? '');
3303
+ }
3304
+
3305
+ // Store original content when policy loads
3306
+ function storeOriginalContent() {
3307
+ originalFileContents = {};
3308
+ changedFiles.clear();
3309
+
3310
+ // Store original file contents
3311
+ originalFileContents['logstash.yml'] = window.policyFileContents['logstash.yml'] || '';
3312
+ originalFileContents['jvm.options'] = window.policyFileContents['jvm.options'] || '';
3313
+ originalFileContents['log4j2.properties'] = window.policyFileContents['log4j2.properties'] || '';
3314
+ const ymlFormActive = window.policyCurrentFile === 'logstash.yml'
3315
+ && document.getElementById('formModeBtn')?.classList.contains('active');
3316
+ originalFormYml = ymlFormActive ? formToYml() : null;
3317
+
3318
+ // Store original Policy Config form fields (paths, simulate source, etc.)
3319
+ POLICY_CONFIG_FIELD_IDS.forEach((id) => {
3320
+ originalFileContents[id] = policyFieldValue(document.getElementById(id));
3321
+ });
3322
+
3323
+ // Reset all visual indicators
3324
+ updateChangeIndicators();
3325
+ }
3326
+
3327
+ // Get current content for a file
3328
+ function getCurrentContent(file) {
3329
+ // Check if this file is currently being edited in the code editor
3330
+ const isCurrentlyEditing = window.policyCurrentFile === file;
3331
+
3332
+ if (file === 'logstash.yml' && isCurrentlyEditing) {
3333
+ // For logstash.yml, check current mode
3334
+ const currentMode = document.getElementById('formModeBtn')?.classList.contains('active') ? 'form' : 'code';
3335
+
3336
+ if (currentMode === 'form') {
3337
+ // Convert form to YAML
3338
+ try {
3339
+ return formToYml() || '';
3340
+ } catch (error) {
3341
+ console.error('Error converting form to YAML:', error);
3342
+ return '';
3343
+ }
3344
+ } else {
3345
+ // Get from code editor
3346
+ return window.policyEditor ? window.policyEditor.getValue() : '';
3347
+ }
3348
+ } else if (isCurrentlyEditing && file === 'jvm.options') {
3349
+ // Use DOM to check mode (currentMode is a closure variable, not in scope here)
3350
+ const jvmMode = document.getElementById('formModeBtn')?.classList.contains('active') ? 'form' : 'code';
3351
+ if (jvmMode === 'code' && window.policyEditor) {
3352
+ return window.policyEditor.getValue();
3353
+ }
3354
+ return window.policyFileContents['jvm.options'] || '';
3355
+ } else if (isCurrentlyEditing && window.policyEditor) {
3356
+ // For other files currently being edited, get from editor
3357
+ return window.policyEditor.getValue();
3358
+ } else {
3359
+ // For files not currently being edited, get from stored contents
3360
+ return window.policyFileContents[file] || '';
3361
+ }
3362
+ }
3363
+
3364
+ // Check if a file has changes
3365
+ function hasFileChanged(file) {
3366
+ const original = originalFileContents[file] || '';
3367
+ const current = getCurrentContent(file);
3368
+ if (file === 'logstash.yml' && originalFormYml !== null && current === originalFormYml) {
3369
+ return false;
3370
+ }
3371
+ return original !== current;
3372
+ }
3373
+
3374
+ // Detect changes and update indicators
3375
+ function detectChanges() {
3376
+ const files = ['logstash.yml', 'jvm.options', 'log4j2.properties'];
3377
+ changedFiles.clear();
3378
+
3379
+ files.forEach(file => {
3380
+ if (hasFileChanged(file)) {
3381
+ changedFiles.add(file);
3382
+ }
3383
+ });
3384
+
3385
+ // Check Policy Config field changes (paths, keystore env, simulate source, ports, …)
3386
+ let configChanged = false;
3387
+ POLICY_CONFIG_FIELD_IDS.forEach((id) => {
3388
+ const el = document.getElementById(id);
3389
+ const current = policyFieldValue(el);
3390
+ const original = originalFileContents[id] ?? '';
3391
+ const fieldChanged = current !== original;
3392
+ if (el) {
3393
+ if (fieldChanged) {
3394
+ el.classList.add('field-modified');
3395
+ } else {
3396
+ el.classList.remove('field-modified');
3397
+ }
3398
+ }
3399
+ if (fieldChanged) configChanged = true;
3400
+ });
3401
+ if (configChanged) {
3402
+ changedFiles.add('settings');
3403
+ }
3404
+
3405
+ updateChangeIndicators();
3406
+ }
3407
+
3408
+ // Update all visual indicators
3409
+ function updateChangeIndicators() {
3410
+ const selected = document.getElementById('policySelect')?.selectedOptions?.[0];
3411
+ const hasChanges = changedFiles.size > 0 || isDraftPolicyOption(selected) || !!window._policyDraftUnsaved;
3412
+ const saveBtn = document.getElementById('saveBtn');
3413
+ const unsavedIndicator = document.getElementById('unsavedChangesIndicator');
3414
+ const policyConfigIndicator = document.getElementById('policyConfigChangedIndicator');
3415
+
3416
+ // Update Save button glow
3417
+ if (hasChanges) {
3418
+ saveBtn?.classList.add('save-button-glow');
3419
+ unsavedIndicator?.classList.remove('hidden');
3420
+ } else {
3421
+ saveBtn?.classList.remove('save-button-glow');
3422
+ unsavedIndicator?.classList.add('hidden');
3423
+ }
3424
+
3425
+ // Update policy config indicator
3426
+ if (changedFiles.has('settings')) {
3427
+ policyConfigIndicator?.classList.remove('hidden');
3428
+ } else {
3429
+ policyConfigIndicator?.classList.add('hidden');
3430
+ // Clear purple outlines when config is clean
3431
+ if (typeof POLICY_CONFIG_FIELD_IDS !== 'undefined') {
3432
+ POLICY_CONFIG_FIELD_IDS.forEach((id) => {
3433
+ document.getElementById(id)?.classList.remove('field-modified');
3434
+ });
3435
+ }
3436
+ }
3437
+
3438
+ // Update tab indicators
3439
+ updateTabIndicators();
3440
+ }
3441
+
3442
+ // Update tab change indicators
3443
+ function updateTabIndicators() {
3444
+ const tabs = {
3445
+ 'logstash.yml': document.querySelector('[data-file="logstash.yml"]'),
3446
+ 'jvm.options': document.querySelector('[data-file="jvm.options"]'),
3447
+ 'log4j2.properties': document.querySelector('[data-file="log4j2.properties"]')
3448
+ };
3449
+
3450
+ Object.keys(tabs).forEach(file => {
3451
+ const tab = tabs[file];
3452
+ if (tab) {
3453
+ if (changedFiles.has(file)) {
3454
+ tab.classList.add('tab-changed');
3455
+ } else {
3456
+ tab.classList.remove('tab-changed');
3457
+ }
3458
+ }
3459
+ });
3460
+ }
3461
+
3462
+ // Hook up change detection to form inputs
3463
+ function setupChangeDetection() {
3464
+ // Monitor form inputs for logstash.yml
3465
+ const formInputs = document.querySelectorAll('#formModeEditor input, #formModeEditor select, #formModeEditor textarea');
3466
+ formInputs.forEach(input => {
3467
+ input.addEventListener('input', () => {
3468
+ detectChanges();
3469
+ });
3470
+ input.addEventListener('change', () => {
3471
+ detectChanges();
3472
+ });
3473
+ });
3474
+
3475
+ // Monitor all Policy Config fields (paths, simulate source, ports, …)
3476
+ POLICY_CONFIG_FIELD_IDS.forEach((id) => {
3477
+ const el = document.getElementById(id);
3478
+ if (!el) return;
3479
+ const handler = () => {
3480
+ if (id === 'logsPath') checkConfigNotifications();
3481
+ if (id === 'settingsPath' || id === 'binaryPath' || id === 'logsPath') {
3482
+ checkPathPermissionNotifications();
3483
+ }
3484
+ if (id === 'logstashSource' && typeof toggleVersionFieldsVisibility === 'function') {
3485
+ toggleVersionFieldsVisibility();
3486
+ }
3487
+ detectChanges();
3488
+ };
3489
+ el.addEventListener('input', handler);
3490
+ el.addEventListener('change', handler);
3491
+ });
3492
+
3493
+ // Monitor code editor changes
3494
+ if (window.policyEditor) {
3495
+ window.policyEditor.on('change', () => {
3496
+ detectChanges();
3497
+ });
3498
+ }
3499
+ }
3500
+
3501
+ // Reset change tracking after save
3502
+ function resetChangeTracking() {
3503
+ storeOriginalContent();
3504
+ }
3505
+
3506
+ // Write the JVM Xms/Xmx input values back into the jvm.options file content
3507
+ function applyJvmHeapToContent() {
3508
+ const xmsInput = document.getElementById('jvmXmsInput');
3509
+ const xmxInput = document.getElementById('jvmXmxInput');
3510
+ const xms = parseInt(xmsInput?.value, 10);
3511
+ const xmx = parseInt(xmxInput?.value, 10);
3512
+
3513
+ let content = window.policyFileContents['jvm.options'] || '';
3514
+
3515
+ if (xms >= 1) {
3516
+ const hasXms = /-Xms\d+[gGmM]/m.test(content);
3517
+ if (hasXms) { content = content.replace(/-Xms\d+[gGmM]/gm, `-Xms${xms}g`); }
3518
+ else { content = `-Xms${xms}g\n` + content; }
3519
+ }
3520
+
3521
+ if (xmx >= 1) {
3522
+ const hasXmx = /-Xmx\d+[gGmM]/m.test(content);
3523
+ if (hasXmx) { content = content.replace(/-Xmx\d+[gGmM]/gm, `-Xmx${xmx}g`); }
3524
+ else { content = `-Xmx${xmx}g\n` + content; }
3525
+ }
3526
+
3527
+ window.policyFileContents['jvm.options'] = content;
3528
+ }
3529
+
3530
+ // Show or hide the heap mismatch banner and update the bell
3531
+ function updateJvmHeapMismatchWarning() {
3532
+ const xmsVal = document.getElementById('jvmXmsInput')?.value;
3533
+ const xmxVal = document.getElementById('jvmXmxInput')?.value;
3534
+ const banner = document.getElementById('jvmMismatchBanner');
3535
+ const mismatch = xmsVal && xmxVal && xmsVal !== xmxVal;
3536
+
3537
+ if (banner) {
3538
+ if (mismatch) { banner.classList.remove('hidden'); }
3539
+ else { banner.classList.add('hidden'); }
3540
+ }
3541
+
3542
+ jvmNotifications = mismatch ? [{
3543
+ type: 'warning',
3544
+ title: 'Heap Size Mismatch',
3545
+ message: '-Xms and -Xmx should be equal to avoid performance issues'
3546
+ }] : [];
3547
+ refreshBellNotifications();
3548
+ }
3549
+
3550
+ // Validate JVM heap settings - ensure Initial Space doesn't exceed Total Space
3551
+ function validateJvmHeapSettings() {
3552
+ const xmsInput = document.getElementById('jvmXmsInput');
3553
+ const xmxInput = document.getElementById('jvmXmxInput');
3554
+
3555
+ if (!xmsInput || !xmxInput) return;
3556
+
3557
+ const xms = parseInt(xmsInput.value, 10);
3558
+ const xmx = parseInt(xmxInput.value, 10);
3559
+
3560
+ // If both values are set and Initial Space is larger than Total Space
3561
+ if (xms && xmx && xms > xmx) {
3562
+ // Set Initial Space to match Total Space
3563
+ xmsInput.value = xmx;
3564
+
3565
+ // Show toast notification
3566
+ showToast('Initial space cannot be larger than total space. Setting initial to be the same as total.', 'warning');
3567
+
3568
+ // Update the mismatch warning after adjustment
3569
+ updateJvmHeapMismatchWarning();
3570
+ }
3571
+ }
3572
+
3573
+ // Note: All guide-related functions have been moved to logstashyml_guides.js
3574
+
3575
+ // Load nodes for the current policy.
3576
+ // `quiet` suppresses toasts, for the background poll below — a flaky network
3577
+ // would otherwise stack a new error toast every 10 seconds.
3578
+ function loadPolicyNodes({ quiet = false } = {}) {
3579
+ const policySelect = document.getElementById('policySelect');
3580
+ const selectedOption = policySelect.options[policySelect.selectedIndex];
3581
+ const policyId = selectedOption.dataset.policyId;
3582
+
3583
+ if (!policyId) {
3584
+ console.error('No policy ID available');
3585
+ return;
3586
+ }
3587
+
3588
+ fetch(`/ConnectionManager/GetPolicyNodes/?policy_id=${policyId}`)
3589
+ .then(response => response.json())
3590
+ .then(data => {
3591
+ if (data.success) {
3592
+ renderPolicyNodes(data.nodes);
3593
+ } else {
3594
+ console.error('Error loading nodes:', data.error);
3595
+ if (!quiet) showToast(data.error || 'Failed to load nodes', 'error');
3596
+ }
3597
+ })
3598
+ .catch(error => {
3599
+ console.error('Error loading nodes:', error);
3600
+ if (!quiet) showToast('Failed to load nodes', 'error');
3601
+ });
3602
+ }
3603
+
3604
+ // The Agents table has no live channel of its own — unlike the Connections
3605
+ // page, which has an SSE stream — so poll while it is on screen. That is what
3606
+ // keeps the LS version pill current after Logstash is upgraded on a host.
3607
+ // 10s rather than the stream's 5s: GetPolicyNodes does per-node SNMP and CPM
3608
+ // lookups, and this is a fetch per client rather than work the server is
3609
+ // already doing.
3610
+ const NODES_POLL_MS = 10000;
3611
+ let _nodesPollTimer = null;
3612
+
3613
+ function startPolicyNodesPolling() {
3614
+ stopPolicyNodesPolling();
3615
+ _nodesPollTimer = setInterval(() => {
3616
+ // A hidden tab still fires intervals. Skip the fetch rather than the
3617
+ // timer, so polling resumes the moment the tab is focused again.
3618
+ if (document.hidden) return;
3619
+ const nodesView = document.getElementById('nodesView');
3620
+ if (!nodesView || nodesView.classList.contains('hidden')) {
3621
+ stopPolicyNodesPolling();
3622
+ return;
3623
+ }
3624
+ loadPolicyNodes({ quiet: true });
3625
+ }, NODES_POLL_MS);
3626
+ }
3627
+
3628
+ function stopPolicyNodesPolling() {
3629
+ if (_nodesPollTimer !== null) {
3630
+ clearInterval(_nodesPollTimer);
3631
+ _nodesPollTimer = null;
3632
+ }
3633
+ }
3634
+
3635
+ // Render nodes in the table
3636
+ function renderPolicyNodes(nodes) {
3637
+ const tbody = document.getElementById('nodesTableBody');
3638
+ if (!tbody) return;
3639
+
3640
+ if (!nodes || nodes.length === 0) {
3641
+ tbody.innerHTML = `
3642
+ <tr>
3643
+ <td colspan="4" class="px-4 py-8 text-center text-gray-400">
3644
+ <div class="flex flex-col items-center gap-2">
3645
+ <svg class="w-12 h-12 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
3646
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 12h14M5 12a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v4a2 2 0 01-2 2M5 12a2 2 0 00-2 2v4a2 2 0 002 2h14a2 2 0 002-2v-4a2 2 0 00-2-2m-2-4h.01M17 16h.01" />
3647
+ </svg>
3648
+ <p>No agents found</p>
3649
+ <p class="text-sm">Agents will appear here when they enroll with this policy</p>
3650
+ </div>
3651
+ </td>
3652
+ </tr>
3653
+ `;
3654
+ return;
3655
+ }
3656
+
3657
+ tbody.innerHTML = nodes.map(node => {
3658
+ // Involvement badges: LogstashAgent always; CPM if policy enables it;
3659
+ // SNMP if this agent has Agent-mode SNMP networks (merged list).
3660
+ const badges = [
3661
+ `<span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-purple-500/15 text-purple-300 border border-purple-500/30">LogstashAgent</span>`
3662
+ ];
3663
+ if (node.logstash_version) {
3664
+ badges.push(`<span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-cyan-500/15 text-cyan-300 border border-cyan-500/30" title="Logstash ${node.logstash_version}">LS ${node.logstash_version}</span>`);
3665
+ }
3666
+ if (node.cpm_enabled) {
3667
+ badges.push(`<span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-500/15 text-blue-300 border border-blue-500/30">CPM</span>`);
3668
+ }
3669
+ if (node.snmp_networks && node.snmp_networks.length) {
3670
+ const title = node.snmp_networks.join(', ');
3671
+ badges.push(`<span title="${title}" class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-emerald-500/15 text-emerald-300 border border-emerald-500/30">SNMP (${node.snmp_networks.length})</span>`);
3672
+ }
3673
+ return `
3674
+ <tr class="hover:bg-gray-700/50 transition-colors">
3675
+ <td class="px-4 py-4 whitespace-nowrap text-sm text-gray-300">
3676
+ <div class="flex flex-col items-center">
3677
+ <div class="rounded-lg p-2" style="background: radial-gradient(circle, rgba(168, 85, 247, 0.15) 0%, rgba(168, 85, 247, 0.05) 70%, transparent 100%);">
3678
+ <img src="/static/images/LogstashIcon.png" alt="Agent" width="52" height="52" class="inline-block">
3679
+ </div>
3680
+ <span class="text-xs text-gray-500 mt-1">LogstashAgent</span>
3681
+ </div>
3682
+ </td>
3683
+ <td class="px-4 py-4 text-sm font-medium text-white">
3684
+ <div class="flex flex-col">
3685
+ <span>${node.name}</span>
3686
+ ${node.agent_version ? `
3687
+ <div class="flex items-center gap-2 mt-0.5">
3688
+ <span class="text-xs text-gray-500">v${node.agent_version}</span>
3689
+ </div>
3690
+ ` : ''}
3691
+ <div class="flex flex-wrap items-center gap-1 mt-1.5">${badges.join('')}</div>
3692
+ </div>
3693
+ </td>
3694
+ <td class="px-4 py-4 whitespace-nowrap text-sm text-gray-300">${node.host || '—'}</td>
3695
+ <td class="px-4 py-4 whitespace-nowrap text-sm text-gray-300">
3696
+ <span class="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium ${node.status_class}">
3697
+ ${node.status.charAt(0).toUpperCase() + node.status.slice(1)}
3698
+
3699
+ </span>
3700
+ </td>
3701
+ </tr>
3702
+ `;
3703
+ }).join('');
3704
+ }
3705
+
3706
+ // ---------------------------------------------------------------------------
3707
+ // Unsaved-changes navigation guard
3708
+ // ---------------------------------------------------------------------------
3709
+
3710
+ // In-app link clicks → custom modal
3711
+ document.addEventListener('click', function(e) {
3712
+ if (changedFiles.size === 0) return;
3713
+
3714
+ const link = e.target.closest('a[href]');
3715
+ if (!link) return;
3716
+
3717
+ const href = link.getAttribute('href');
3718
+ // Skip anchors, javascript: pseudo-links, and new-tab links
3719
+ if (!href || href.startsWith('#') || href.startsWith('javascript:') || link.target === '_blank') return;
3720
+
3721
+ e.preventDefault();
3722
+
3723
+ ConfirmationModal.show(
3724
+ 'You have unsaved changes that will be lost if you leave this page.',
3725
+ 'Unsaved Changes',
3726
+ 'Leave Page',
3727
+ null,
3728
+ false,
3729
+ 'Stay'
3730
+ ).then(confirmed => {
3731
+ if (confirmed) {
3732
+ // Bypass guard on the way out
3733
+ changedFiles.clear();
3734
+ window.location.href = href;
3735
+ }
3736
+ });
3737
+ }, true); // capture phase so we intercept before any other handlers
3738
+
3739
+ // Browser close / refresh / address-bar navigation → native dialog
3740
+ window.addEventListener('beforeunload', function(e) {
3741
+ if (changedFiles.size > 0) {
3742
+ e.preventDefault();
3743
+ e.returnValue = '';
3744
+ }
3745
+ });
3746
+