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
API/pipelines_views.py ADDED
@@ -0,0 +1,1224 @@
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
+ """REST API views for pipeline management.
6
+
7
+ Agent/policy pipelines (Django ORM — identified by integer id)
8
+ --------------------------------------------------------------
9
+ GET /api/pipelines/?policy_id=X pipeline_list
10
+ POST /api/pipelines/ pipeline_list
11
+ GET /api/pipelines/{id}/ pipeline_detail
12
+ PUT /api/pipelines/{id}/ pipeline_detail
13
+ DELETE /api/pipelines/{id}/ pipeline_detail
14
+ POST /api/pipelines/policies/{id}/deploy/ policy_deploy
15
+
16
+ Centralized Pipeline Management (CPM) Logstash pipelines (identified by name)
17
+ ------------------------------------------------------------------------------
18
+ Logstash pipelines stored through the Elasticsearch ``_logstash/pipeline`` API
19
+ and pulled by Logstash nodes running CPM. Not Elasticsearch ingest pipelines.
20
+ ``/api/pipelines/es/...`` is a deprecated alias for the same views.
21
+
22
+ GET /api/pipelines/centralized/{connection_id}/ centralized_pipeline_list
23
+ POST /api/pipelines/centralized/{connection_id}/ centralized_pipeline_list
24
+ GET /api/pipelines/centralized/{connection_id}/{name}/ centralized_pipeline_detail
25
+ PUT /api/pipelines/centralized/{connection_id}/{name}/ centralized_pipeline_detail
26
+ DELETE /api/pipelines/centralized/{connection_id}/{name}/ centralized_pipeline_detail
27
+
28
+ Lookup
29
+ ------
30
+ GET /api/pipelines/find/?name=X pipeline_find
31
+ GET /api/pipelines/recent/ pipeline_recent
32
+
33
+ Simulation
34
+ ----------
35
+ POST /api/pipelines/simulate/ pipeline_simulate
36
+ """
37
+
38
+ import difflib
39
+ import json
40
+ import logging
41
+ import time
42
+ from concurrent.futures import ThreadPoolExecutor
43
+ from datetime import datetime, timezone
44
+
45
+ import requests
46
+ from django.core.exceptions import ValidationError
47
+ from django.db import IntegrityError, OperationalError, transaction
48
+ from django.db.models import F
49
+ from django.http import JsonResponse
50
+ from django.views.decorators.csrf import csrf_exempt
51
+
52
+ from Common import logstash_config_parse
53
+ from Common.elastic_utils import get_elastic_connection
54
+ from PipelineManager.models import Connection, Pipeline, Policy, SimulationResult
55
+ from PipelineManager.simulation import new_run_id, send_simulation_event, start_simulation
56
+
57
+ from API.auth import api_require_admin, api_require_auth, parse_request_body
58
+ from API.simulation_detail import DETAIL_LEVELS, component_index, run_status, shape_results
59
+
60
+ logger = logging.getLogger(__name__)
61
+
62
+ _PIPELINE_WRITE_FIELDS = frozenset([
63
+ 'name', 'description', 'lscl',
64
+ 'pipeline_workers', 'pipeline_batch_size', 'pipeline_batch_delay',
65
+ 'queue_type', 'queue_max_bytes', 'queue_checkpoint_writes',
66
+ ])
67
+
68
+ _SIMULATE_MAX_TIMEOUT = 180 # seconds
69
+ _SIMULATE_DEFAULT_TIMEOUT = 30
70
+ _SIMULATE_MAX_EVENTS = 100
71
+ _EMPTY_FINAL_GRACE = 1.0 # seconds
72
+
73
+ _FIND_ES_TIMEOUT = 10 # seconds per connection, queried in parallel
74
+
75
+
76
+ # ---------------------------------------------------------------------------
77
+ # Serialization helpers
78
+ # ---------------------------------------------------------------------------
79
+
80
+ def _pipeline_data(pipeline):
81
+ """Full serialization of a Pipeline model instance."""
82
+ return {
83
+ 'id': pipeline.id,
84
+ 'policy_id': pipeline.policy_id,
85
+ 'name': pipeline.name,
86
+ 'managed_by': pipeline.managed_by,
87
+ 'description': pipeline.description,
88
+ 'lscl': pipeline.lscl,
89
+ 'pipeline_hash': pipeline.pipeline_hash,
90
+ 'last_updated': pipeline.last_updated.isoformat(),
91
+ 'revision_number': pipeline.revision_number,
92
+ 'pipeline_workers': pipeline.pipeline_workers,
93
+ 'pipeline_batch_size': pipeline.pipeline_batch_size,
94
+ 'pipeline_batch_delay': pipeline.pipeline_batch_delay,
95
+ 'queue_type': pipeline.queue_type,
96
+ 'queue_max_bytes': pipeline.queue_max_bytes,
97
+ 'queue_checkpoint_writes': pipeline.queue_checkpoint_writes,
98
+ 'no_input': pipeline.no_input,
99
+ 'non_reloadable': pipeline.non_reloadable,
100
+ }
101
+
102
+
103
+ def _pipeline_list_data(pipeline):
104
+ """Lighter serialization for list responses."""
105
+ return {
106
+ 'id': pipeline.id,
107
+ 'policy_id': pipeline.policy_id,
108
+ 'name': pipeline.name,
109
+ 'managed_by': pipeline.managed_by,
110
+ 'description': pipeline.description,
111
+ 'pipeline_hash': pipeline.pipeline_hash,
112
+ 'last_updated': pipeline.last_updated.isoformat(),
113
+ 'revision_number': pipeline.revision_number,
114
+ 'no_input': pipeline.no_input,
115
+ 'non_reloadable': pipeline.non_reloadable,
116
+ }
117
+
118
+
119
+ def _apply_pipeline_fields(data, pipeline):
120
+ """Apply parsed request data onto a Pipeline instance (mutates in place)."""
121
+ if 'name' in data:
122
+ new_name = (data['name'] or '').strip()
123
+ # L3 fix: an empty name on update was silently ignored; raise ValueError
124
+ # so the caller returns 400.
125
+ if not new_name:
126
+ raise ValueError('name cannot be empty.')
127
+ pipeline.name = new_name
128
+ if 'description' in data:
129
+ pipeline.description = data['description'] or ''
130
+ if 'lscl' in data:
131
+ pipeline.lscl = data['lscl'] or ''
132
+
133
+ for int_field in ('pipeline_workers', 'pipeline_batch_size',
134
+ 'pipeline_batch_delay', 'queue_checkpoint_writes'):
135
+ if int_field in data and data[int_field] is not None:
136
+ # M20 fix: __setattr__ bypasses Django field descriptors; use setattr.
137
+ setattr(pipeline, int_field, int(data[int_field]))
138
+
139
+ for str_field in ('queue_type', 'queue_max_bytes'):
140
+ if str_field in data and data[str_field] is not None:
141
+ setattr(pipeline, str_field, str(data[str_field]))
142
+
143
+
144
+ # ---------------------------------------------------------------------------
145
+ # GET/POST /api/pipelines/ — agent pipeline list + create
146
+ # ---------------------------------------------------------------------------
147
+
148
+ @csrf_exempt
149
+ def pipeline_list(request):
150
+ """List agent pipelines for a policy, or create a new one.
151
+
152
+ GET /api/pipelines/?policy_id=X
153
+ Returns user-managed pipelines for the given policy.
154
+ Requires ``policy_id`` query parameter. Any authenticated user.
155
+
156
+ POST /api/pipelines/
157
+ Create a pipeline. Required body fields: ``policy_id``, ``name``, ``lscl``.
158
+ Sets ``policy.has_undeployed_changes = True``. Admin only.
159
+ """
160
+ if request.method == 'GET':
161
+ return _list_pipelines(request)
162
+ if request.method == 'POST':
163
+ return _create_pipeline(request)
164
+ return JsonResponse({'success': False, 'error': 'Method not allowed'}, status=405)
165
+
166
+
167
+ @api_require_auth
168
+ def _list_pipelines(request):
169
+ policy_id = request.GET.get('policy_id', '').strip()
170
+ if not policy_id:
171
+ return JsonResponse(
172
+ {'success': False, 'error': 'policy_id query parameter is required.'},
173
+ status=400,
174
+ )
175
+
176
+ try:
177
+ policy = Policy.objects.get(pk=policy_id)
178
+ except Policy.DoesNotExist:
179
+ return JsonResponse({'success': False, 'error': 'Policy not found.'}, status=404)
180
+
181
+ # H18 fix: managed_by was passed directly from query params, letting any
182
+ # caller filter SNMP or other system pipelines. Restrict to known values.
183
+ _ALLOWED_MANAGED_BY = frozenset({'user', 'snmp', 'library'})
184
+ managed_by = request.GET.get('managed_by', 'user').strip() or 'user'
185
+ if managed_by not in _ALLOWED_MANAGED_BY:
186
+ managed_by = 'user'
187
+ pipelines = list(
188
+ policy.pipelines.filter(managed_by=managed_by).order_by('name')
189
+ )
190
+ return JsonResponse({
191
+ 'policy_id': policy.id,
192
+ 'policy_name': policy.name,
193
+ 'has_undeployed_changes': policy.has_undeployed_changes,
194
+ 'pipelines': [_pipeline_list_data(p) for p in pipelines],
195
+ 'count': len(pipelines),
196
+ })
197
+
198
+
199
+ @api_require_admin
200
+ def _create_pipeline(request):
201
+ data = parse_request_body(request)
202
+
203
+ policy_id = data.get('policy_id')
204
+ name = (data.get('name') or '').strip()
205
+ lscl = data.get('lscl', '')
206
+
207
+ if not policy_id:
208
+ return JsonResponse({'success': False, 'error': 'policy_id is required.'}, status=400)
209
+ if not name:
210
+ return JsonResponse({'success': False, 'error': 'name is required.'}, status=400)
211
+ if not lscl:
212
+ return JsonResponse({'success': False, 'error': 'lscl is required.'}, status=400)
213
+
214
+ try:
215
+ policy = Policy.objects.get(pk=policy_id)
216
+ except Policy.DoesNotExist:
217
+ return JsonResponse({'success': False, 'error': 'Policy not found.'}, status=404)
218
+
219
+ pipeline = Pipeline(
220
+ policy=policy,
221
+ name=name,
222
+ lscl=lscl,
223
+ managed_by='user',
224
+ )
225
+
226
+ try:
227
+ _apply_pipeline_fields(data, pipeline)
228
+ except (ValueError, TypeError) as exc:
229
+ return JsonResponse({'success': False, 'error': f'Invalid field value: {exc}'}, status=400)
230
+
231
+ try:
232
+ pipeline.save()
233
+ except ValidationError as exc:
234
+ errors = exc.message_dict if hasattr(exc, 'message_dict') else {'error': exc.messages}
235
+ return JsonResponse({'success': False, 'error': errors}, status=400)
236
+ except IntegrityError as exc:
237
+ return JsonResponse({'success': False, 'error': str(exc)}, status=409)
238
+ except Exception as exc:
239
+ logger.error("API create pipeline: %s", exc)
240
+ return JsonResponse({'success': False, 'error': 'An internal error occurred. Check server logs.'}, status=500)
241
+
242
+ policy.has_undeployed_changes = True
243
+ policy.save(update_fields=['has_undeployed_changes'])
244
+
245
+ logger.info("API: pipeline '%s' created in policy %s by %s.", name, policy_id, request.user.username)
246
+ return JsonResponse({
247
+ 'success': True,
248
+ 'id': pipeline.id,
249
+ 'message': 'Pipeline created successfully.',
250
+ }, status=201)
251
+
252
+
253
+ # ---------------------------------------------------------------------------
254
+ # GET/PUT/DELETE /api/pipelines/{id}/ — agent pipeline detail
255
+ # ---------------------------------------------------------------------------
256
+
257
+ @csrf_exempt
258
+ def pipeline_detail(request, pipeline_id):
259
+ """Read, update, or delete a single agent pipeline.
260
+
261
+ GET /api/pipelines/{id}/ any authenticated user
262
+ PUT /api/pipelines/{id}/ admin only
263
+ DELETE /api/pipelines/{id}/ admin only
264
+ """
265
+ if request.method == 'GET':
266
+ return _get_pipeline(request, pipeline_id)
267
+ if request.method == 'PUT':
268
+ return _update_pipeline(request, pipeline_id)
269
+ if request.method == 'DELETE':
270
+ return _delete_pipeline(request, pipeline_id)
271
+ return JsonResponse({'success': False, 'error': 'Method not allowed'}, status=405)
272
+
273
+
274
+ @api_require_auth
275
+ def _get_pipeline(request, pipeline_id):
276
+ try:
277
+ pipeline = Pipeline.objects.select_related('policy').get(pk=pipeline_id)
278
+ except Pipeline.DoesNotExist:
279
+ return JsonResponse({'success': False, 'error': 'Pipeline not found.'}, status=404)
280
+ return JsonResponse({'success': True, 'pipeline': _pipeline_data(pipeline)})
281
+
282
+
283
+ @api_require_admin
284
+ def _update_pipeline(request, pipeline_id):
285
+ try:
286
+ pipeline = Pipeline.objects.select_related('policy').get(pk=pipeline_id)
287
+ except Pipeline.DoesNotExist:
288
+ return JsonResponse({'success': False, 'error': 'Pipeline not found.'}, status=404)
289
+
290
+ data = parse_request_body(request)
291
+
292
+ try:
293
+ _apply_pipeline_fields(data, pipeline)
294
+ except (ValueError, TypeError) as exc:
295
+ return JsonResponse({'success': False, 'error': f'Invalid field value: {exc}'}, status=400)
296
+
297
+ try:
298
+ pipeline.save()
299
+ except ValidationError as exc:
300
+ errors = exc.message_dict if hasattr(exc, 'message_dict') else {'error': exc.messages}
301
+ return JsonResponse({'success': False, 'error': errors}, status=400)
302
+ except IntegrityError as exc:
303
+ return JsonResponse({'success': False, 'error': str(exc)}, status=409)
304
+ except Exception as exc:
305
+ logger.error("API update pipeline %s: %s", pipeline_id, exc)
306
+ return JsonResponse({'success': False, 'error': 'An internal error occurred. Check server logs.'}, status=500)
307
+
308
+ policy = pipeline.policy
309
+ policy.has_undeployed_changes = True
310
+ policy.save(update_fields=['has_undeployed_changes'])
311
+
312
+ logger.info("API: pipeline %s updated by %s.", pipeline_id, request.user.username)
313
+ return JsonResponse({
314
+ 'success': True,
315
+ 'id': pipeline.id,
316
+ 'message': 'Pipeline saved successfully.',
317
+ })
318
+
319
+
320
+ @api_require_admin
321
+ def _delete_pipeline(request, pipeline_id):
322
+ try:
323
+ pipeline = Pipeline.objects.select_related('policy').get(pk=pipeline_id)
324
+ except Pipeline.DoesNotExist:
325
+ return JsonResponse({'success': False, 'error': 'Pipeline not found.'}, status=404)
326
+
327
+ name = pipeline.name
328
+ policy = pipeline.policy
329
+ pipeline.delete()
330
+
331
+ policy.has_undeployed_changes = True
332
+ policy.save(update_fields=['has_undeployed_changes'])
333
+
334
+ logger.warning("API: pipeline '%s' (ID: %s) deleted by %s.", name, pipeline_id, request.user.username)
335
+ return JsonResponse({'success': True, 'message': f"Pipeline '{name}' deleted."})
336
+
337
+
338
+ # ---------------------------------------------------------------------------
339
+ # POST /api/pipelines/policies/{policy_id}/deploy/ — deploy a policy
340
+ # ---------------------------------------------------------------------------
341
+
342
+ @csrf_exempt
343
+ @api_require_admin
344
+ def policy_deploy(request, policy_id):
345
+ """Snapshot the current user pipelines as a new revision.
346
+
347
+ Increments ``current_revision_number``, writes a ``Revision`` row, sets
348
+ ``last_deployed_at``. Agents pick up the change on next check-in.
349
+
350
+ POST /api/pipelines/policies/{policy_id}/deploy/
351
+ """
352
+ if request.method != 'POST':
353
+ return JsonResponse({'success': False, 'error': 'Method not allowed'}, status=405)
354
+
355
+ try:
356
+ policy = Policy.objects.get(pk=policy_id)
357
+ except Policy.DoesNotExist:
358
+ return JsonResponse({'success': False, 'error': 'Policy not found.'}, status=404)
359
+
360
+ from PipelineManager.models import Revision
361
+
362
+ # H15 fix: a non-atomic read-increment-write allowed two concurrent deploys
363
+ # to get the same revision number. Keep the F() increment, snapshot, Revision
364
+ # insert, and policy update in one atomic block so a later failure cannot
365
+ # leave current_revision_number bumped with no matching Revision row.
366
+ with transaction.atomic():
367
+ Policy.objects.filter(pk=policy.pk).update(
368
+ current_revision_number=F('current_revision_number') + 1
369
+ )
370
+ policy.refresh_from_db(fields=['current_revision_number'])
371
+ new_revision_number = policy.current_revision_number
372
+
373
+ snapshot_data = {
374
+ 'logstash_yml': policy.logstash_yml,
375
+ 'jvm_options': policy.jvm_options,
376
+ 'log4j2_properties': policy.log4j2_properties,
377
+ 'settings_path': policy.settings_path,
378
+ 'logs_path': policy.logs_path,
379
+ 'binary_path': policy.binary_path,
380
+ 'pipelines': list(
381
+ policy.pipelines.filter(managed_by='user').values(*Pipeline.SNAPSHOT_FIELDS)
382
+ ),
383
+ 'keystore': list(
384
+ policy.keystore_entries.filter(managed_by='user').values('key_name', 'key_value')
385
+ ),
386
+ 'keystore_password_hash': policy.keystore_password_hash,
387
+ }
388
+
389
+ Revision.objects.create(
390
+ policy=policy,
391
+ revision_number=new_revision_number,
392
+ snapshot_json=snapshot_data,
393
+ created_by=request.user.username,
394
+ )
395
+
396
+ policy.last_deployed_at = datetime.now(timezone.utc)
397
+ # Bug 5 fix: clear the undeployed-changes flag after a successful deploy.
398
+ policy.has_undeployed_changes = False
399
+ policy.save(update_fields=['last_deployed_at', 'has_undeployed_changes'])
400
+
401
+ logger.info(
402
+ "API: policy '%s' deployed as revision %s by %s.",
403
+ policy.name, new_revision_number, request.user.username,
404
+ )
405
+ return JsonResponse({
406
+ 'success': True,
407
+ 'message': f"Policy deployed as revision {new_revision_number}.",
408
+ 'revision_number': new_revision_number,
409
+ 'policy_id': policy.id,
410
+ 'policy_name': policy.name,
411
+ 'last_deployed_at': policy.last_deployed_at.isoformat(),
412
+ })
413
+
414
+
415
+ # ---------------------------------------------------------------------------
416
+ # GET/POST /api/pipelines/centralized/{connection_id}/ — CPM pipeline list + create
417
+ # ---------------------------------------------------------------------------
418
+
419
+ @csrf_exempt
420
+ def centralized_pipeline_list(request, connection_id):
421
+ """List or create Centralized Pipeline Management Logstash pipelines.
422
+
423
+ These are Logstash pipelines stored via the Elasticsearch
424
+ ``_logstash/pipeline`` API, not Elasticsearch ingest pipelines.
425
+
426
+ GET /api/pipelines/centralized/{connection_id}/
427
+ List all CPM pipelines on the connection. ``?include_lscl=false``
428
+ omits each pipeline's config. Any authenticated user.
429
+
430
+ POST /api/pipelines/centralized/{connection_id}/
431
+ Create a pipeline. Required body fields: ``name``, ``lscl``.
432
+ Admin only.
433
+
434
+ Example:
435
+ curl -H "Authorization: ApiKey $KEY" \\
436
+ https://logstashui.example.com/api/pipelines/centralized/17/
437
+ """
438
+ if request.method == 'GET':
439
+ return _centralized_list_pipelines(request, connection_id)
440
+ if request.method == 'POST':
441
+ return _centralized_create_pipeline(request, connection_id)
442
+ return JsonResponse({'success': False, 'error': 'Method not allowed'}, status=405)
443
+
444
+
445
+ def _check_centralized_connection_exists(connection_id):
446
+ """Return a 404 JsonResponse if the connection row doesn't exist, else None.
447
+
448
+ Bug 4 fix: ``get_elastic_connection`` raises DoesNotExist which previously
449
+ bubbled up as a 502. Checking up-front lets us return the correct 404.
450
+ """
451
+ if not Connection.objects.filter(pk=connection_id).exists():
452
+ return JsonResponse(
453
+ {'success': False, 'error': 'Connection not found.'}, status=404
454
+ )
455
+ return None
456
+
457
+
458
+ @api_require_auth
459
+ def _centralized_list_pipelines(request, connection_id):
460
+ early = _check_centralized_connection_exists(connection_id)
461
+ if early:
462
+ return early
463
+ try:
464
+ es = get_elastic_connection(connection_id)
465
+ raw = es.logstash.get_pipeline()
466
+ except Exception as exc:
467
+ logger.error("API CPM list pipelines (conn %s): %s", connection_id, exc)
468
+ return JsonResponse({'success': False, 'error': str(exc)}, status=502)
469
+
470
+ include_lscl = request.GET.get('include_lscl', 'true').lower() != 'false'
471
+ pipelines = []
472
+ for name, body in (raw or {}).items():
473
+ entry = {
474
+ 'name': name,
475
+ 'description': body.get('description', ''),
476
+ 'last_modified': body.get('last_modified', ''),
477
+ 'username': body.get('username', ''),
478
+ 'pipeline_settings': body.get('pipeline_settings', {}),
479
+ }
480
+ if include_lscl:
481
+ entry['lscl'] = body.get('pipeline', '')
482
+ pipelines.append(entry)
483
+
484
+ return JsonResponse({
485
+ 'connection_id': connection_id,
486
+ 'pipelines': sorted(pipelines, key=lambda p: p['name']),
487
+ 'count': len(pipelines),
488
+ })
489
+
490
+
491
+ @api_require_admin
492
+ def _centralized_create_pipeline(request, connection_id):
493
+ early = _check_centralized_connection_exists(connection_id)
494
+ if early:
495
+ return early
496
+
497
+ data = parse_request_body(request)
498
+ name = (data.get('name') or '').strip()
499
+ lscl = data.get('lscl', '')
500
+
501
+ if not name:
502
+ return JsonResponse({'success': False, 'error': 'name is required.'}, status=400)
503
+ if not lscl:
504
+ return JsonResponse({'success': False, 'error': 'lscl is required.'}, status=400)
505
+
506
+ body = {
507
+ 'description': data.get('description', ''),
508
+ 'last_modified': datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z',
509
+ 'pipeline_metadata': {'version': 1, 'type': 'logstash_pipeline'},
510
+ 'username': request.user.username,
511
+ 'pipeline': lscl,
512
+ 'pipeline_settings': {
513
+ 'pipeline.workers': int(data.get('pipeline_workers', 1)),
514
+ 'pipeline.batch.size': int(data.get('pipeline_batch_size', 128)),
515
+ 'pipeline.batch.delay': int(data.get('pipeline_batch_delay', 50)),
516
+ 'queue.type': data.get('queue_type', 'memory'),
517
+ 'queue.max_bytes': data.get('queue_max_bytes', '1gb'),
518
+ 'queue.checkpoint.writes': int(data.get('queue_checkpoint_writes', 1024)),
519
+ },
520
+ }
521
+
522
+ try:
523
+ es = get_elastic_connection(connection_id)
524
+ es.logstash.put_pipeline(id=name, body=body)
525
+ except Exception as exc:
526
+ logger.error("API CPM create pipeline '%s' (conn %s): %s", name, connection_id, exc)
527
+ return JsonResponse({'success': False, 'error': str(exc)}, status=502)
528
+
529
+ logger.info("API: CPM pipeline '%s' created in conn %s by %s.", name, connection_id, request.user.username)
530
+ return JsonResponse({'success': True, 'name': name, 'message': 'Pipeline created.'}, status=201)
531
+
532
+
533
+ # ---------------------------------------------------------------------------
534
+ # GET/PUT/DELETE /api/pipelines/centralized/{connection_id}/{name}/ — CPM pipeline detail
535
+ # ---------------------------------------------------------------------------
536
+
537
+ @csrf_exempt
538
+ def centralized_pipeline_detail(request, connection_id, name):
539
+ """Read, update, or delete one Centralized Pipeline Management Logstash pipeline.
540
+
541
+ GET /api/pipelines/centralized/{connection_id}/{name}/ any authenticated user
542
+ PUT /api/pipelines/centralized/{connection_id}/{name}/ admin only
543
+ DELETE /api/pipelines/centralized/{connection_id}/{name}/ admin only
544
+
545
+ Example:
546
+ curl -X DELETE -H "Authorization: ApiKey $KEY" \\
547
+ https://logstashui.example.com/api/pipelines/centralized/17/apache-logs/
548
+ """
549
+ # H16 fix: without this guard an unknown connection_id produced a 502 instead
550
+ # of the expected 404 because get_elastic_connection raised DoesNotExist which
551
+ # was caught by the broad `except Exception` in each sub-handler and reported
552
+ # as a connection error rather than a "not found" error.
553
+ early = _check_centralized_connection_exists(connection_id)
554
+ if early:
555
+ return early
556
+
557
+ if request.method == 'GET':
558
+ return _centralized_get_pipeline(request, connection_id, name)
559
+ if request.method == 'PUT':
560
+ return _centralized_update_pipeline(request, connection_id, name)
561
+ if request.method == 'DELETE':
562
+ return _centralized_delete_pipeline(request, connection_id, name)
563
+ return JsonResponse({'success': False, 'error': 'Method not allowed'}, status=405)
564
+
565
+
566
+ @api_require_auth
567
+ def _centralized_get_pipeline(request, connection_id, name):
568
+ try:
569
+ es = get_elastic_connection(connection_id)
570
+ raw = es.logstash.get_pipeline(id=name)
571
+ except Exception as exc:
572
+ status = 404 if '404' in str(exc) or 'not found' in str(exc).lower() else 502
573
+ return JsonResponse({'success': False, 'error': str(exc)}, status=status)
574
+
575
+ body = (raw or {}).get(name, {})
576
+ return JsonResponse({
577
+ 'success': True,
578
+ 'pipeline': {
579
+ 'name': name,
580
+ 'connection_id': connection_id,
581
+ 'description': body.get('description', ''),
582
+ 'lscl': body.get('pipeline', ''),
583
+ 'last_modified': body.get('last_modified', ''),
584
+ 'username': body.get('username', ''),
585
+ 'pipeline_settings': body.get('pipeline_settings', {}),
586
+ },
587
+ })
588
+
589
+
590
+ @api_require_admin
591
+ def _centralized_update_pipeline(request, connection_id, name):
592
+ data = parse_request_body(request)
593
+
594
+ # Fetch current to merge
595
+ try:
596
+ es = get_elastic_connection(connection_id)
597
+ raw = es.logstash.get_pipeline(id=name)
598
+ current = (raw or {}).get(name, {})
599
+ except Exception as exc:
600
+ status = 404 if '404' in str(exc) or 'not found' in str(exc).lower() else 502
601
+ return JsonResponse({'success': False, 'error': str(exc)}, status=status)
602
+
603
+ current_settings = current.get('pipeline_settings', {})
604
+
605
+ body = {
606
+ 'description': data.get('description', current.get('description', '')),
607
+ 'last_modified': datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z',
608
+ 'pipeline_metadata': current.get('pipeline_metadata', {'version': 1, 'type': 'logstash_pipeline'}),
609
+ 'username': request.user.username,
610
+ 'pipeline': data.get('lscl', current.get('pipeline', '')),
611
+ 'pipeline_settings': {
612
+ 'pipeline.workers': int(data.get('pipeline_workers', current_settings.get('pipeline.workers', 1))),
613
+ 'pipeline.batch.size': int(data.get('pipeline_batch_size', current_settings.get('pipeline.batch.size', 128))),
614
+ 'pipeline.batch.delay': int(data.get('pipeline_batch_delay', current_settings.get('pipeline.batch.delay', 50))),
615
+ 'queue.type': data.get('queue_type', current_settings.get('queue.type', 'memory')),
616
+ 'queue.max_bytes': data.get('queue_max_bytes', current_settings.get('queue.max_bytes', '1gb')),
617
+ 'queue.checkpoint.writes': int(data.get('queue_checkpoint_writes', current_settings.get('queue.checkpoint.writes', 1024))),
618
+ },
619
+ }
620
+
621
+ try:
622
+ es.logstash.put_pipeline(id=name, body=body)
623
+ except Exception as exc:
624
+ logger.error("API CPM update pipeline '%s' (conn %s): %s", name, connection_id, exc)
625
+ return JsonResponse({'success': False, 'error': str(exc)}, status=502)
626
+
627
+ logger.info("API: CPM pipeline '%s' updated in conn %s by %s.", name, connection_id, request.user.username)
628
+ return JsonResponse({'success': True, 'name': name, 'message': 'Pipeline updated.'})
629
+
630
+
631
+ @api_require_admin
632
+ def _centralized_delete_pipeline(request, connection_id, name):
633
+ try:
634
+ es = get_elastic_connection(connection_id)
635
+ es.logstash.delete_pipeline(id=name)
636
+ except Exception as exc:
637
+ status = 404 if '404' in str(exc) or 'not found' in str(exc).lower() else 502
638
+ return JsonResponse({'success': False, 'error': str(exc)}, status=status)
639
+
640
+ logger.warning("API: CPM pipeline '%s' deleted from conn %s by %s.", name, connection_id, request.user.username)
641
+ return JsonResponse({'success': True, 'message': f"Pipeline '{name}' deleted."})
642
+
643
+
644
+ # ---------------------------------------------------------------------------
645
+ # GET /api/pipelines/find/ — locate a pipeline by name everywhere
646
+ # ---------------------------------------------------------------------------
647
+
648
+ @api_require_auth
649
+ def pipeline_find(request):
650
+ """Find Logstash pipelines by name in every policy and on every CPM connection.
651
+
652
+ Agent pipelines are searched in every policy except embedded ones, and CPM
653
+ pipelines on every CENTRALIZED connection. Connections that can't be
654
+ listed are reported under ``unreachable`` so callers can tell "not found"
655
+ from "not searched".
656
+
657
+ GET /api/pipelines/find/?name=X any authenticated user
658
+
659
+ ``name`` may be part of a name or a topic such as ``asa``: pipelines whose
660
+ names contain it are returned under ``similar``.
661
+
662
+ Each pipeline in ``matches`` (exact name) and ``similar`` (up to 10 close
663
+ or overlapping names, closest first) is either
664
+ ``{"type": "agent", "name", "pipeline_id", "policy_id", "policy_name",
665
+ "managed_by", "last_modified"}`` or ``{"type": "cpm", "name",
666
+ "connection_id", "connection_name", "last_modified"}``. Its id fields are
667
+ the arguments other pipeline endpoints, including simulate, take.
668
+
669
+ Example:
670
+ curl -H "Authorization: ApiKey $KEY" \\
671
+ "https://logstashui.example.com/api/pipelines/find/?name=asa-new"
672
+ """
673
+ if request.method != 'GET':
674
+ return JsonResponse({'success': False, 'error': 'Method not allowed'}, status=405)
675
+ name = request.GET.get('name', '').strip()
676
+ if not name:
677
+ return JsonResponse(
678
+ {'success': False, 'error': 'name query parameter is required.'}, status=400,
679
+ )
680
+
681
+ candidates, unreachable = _list_all_pipelines()
682
+ return JsonResponse({
683
+ 'success': True,
684
+ 'name': name,
685
+ 'matches': [c for c in candidates if c['name'] == name],
686
+ 'similar': _similar_pipelines(name, candidates),
687
+ 'unreachable': unreachable,
688
+ })
689
+
690
+
691
+ # ---------------------------------------------------------------------------
692
+ # GET /api/pipelines/recent/ — pipelines everywhere, newest change first
693
+ # ---------------------------------------------------------------------------
694
+
695
+ @api_require_auth
696
+ def pipeline_recent(request):
697
+ """List pipelines in every policy and on every CPM connection, most recently modified first.
698
+
699
+ Reads the ``last_modified`` each pipeline already carries; nothing is
700
+ recorded about who changed what.
701
+
702
+ GET /api/pipelines/recent/?limit=20&since=2026-11-01T00:00:00Z any authenticated user
703
+
704
+ Query parameters:
705
+ limit: Maximum pipelines to return (default 20, max 200).
706
+ since: ISO 8601 timestamp; only pipelines modified at or after it.
707
+
708
+ Returns entries in the :func:`pipeline_find` form, plus ``unreachable``
709
+ connections whose pipelines could not be listed.
710
+
711
+ Example:
712
+ curl -H "Authorization: ApiKey $KEY" \\
713
+ "https://logstashui.example.com/api/pipelines/recent/?since=2026-11-01"
714
+ """
715
+ if request.method != 'GET':
716
+ return JsonResponse({'success': False, 'error': 'Method not allowed'}, status=405)
717
+ try:
718
+ limit = int(request.GET.get('limit') or 20)
719
+ except ValueError:
720
+ return JsonResponse({'success': False, 'error': 'limit must be an integer.'}, status=400)
721
+ limit = max(1, min(limit, 200))
722
+ since = None
723
+ if request.GET.get('since'):
724
+ since = _parse_timestamp(request.GET['since'])
725
+ if since is None:
726
+ return JsonResponse(
727
+ {'success': False, 'error': 'since must be an ISO 8601 timestamp.'}, status=400,
728
+ )
729
+
730
+ candidates, unreachable = _list_all_pipelines()
731
+ dated = [(_parse_timestamp(c['last_modified']), c) for c in candidates]
732
+ dated = [(ts, c) for ts, c in dated if ts and (since is None or ts >= since)]
733
+ dated.sort(key=lambda item: item[0], reverse=True)
734
+ return JsonResponse({
735
+ 'success': True,
736
+ 'pipelines': [c for _, c in dated[:limit]],
737
+ 'total': len(dated),
738
+ 'unreachable': unreachable,
739
+ })
740
+
741
+
742
+ def _parse_timestamp(value):
743
+ """Parse an ISO 8601 timestamp to an aware UTC datetime, or None.
744
+
745
+ Examples:
746
+ >>> _parse_timestamp('2026-11-04T15:17:52.688Z').isoformat()
747
+ '2026-11-04T15:17:52.688000+00:00'
748
+ >>> _parse_timestamp('2026-11-01').isoformat()
749
+ '2026-11-01T00:00:00+00:00'
750
+ >>> _parse_timestamp('yesterday') is None
751
+ True
752
+ """
753
+ try:
754
+ parsed = datetime.fromisoformat(str(value).replace('Z', '+00:00'))
755
+ except ValueError:
756
+ return None
757
+ if parsed.tzinfo is None:
758
+ parsed = parsed.replace(tzinfo=timezone.utc)
759
+ return parsed.astimezone(timezone.utc)
760
+
761
+
762
+ def _list_all_pipelines():
763
+ """List agent pipelines (except embedded policies) and CPM pipelines.
764
+
765
+ Returns:
766
+ tuple: ``(pipelines, unreachable)`` in the :func:`pipeline_find` entry form.
767
+ """
768
+ agent_pipelines = (
769
+ Pipeline.objects.select_related('policy')
770
+ .exclude(policy__policy_type=Policy.PolicyType.EMBEDDED)
771
+ .order_by('policy__name', 'name')
772
+ )
773
+ pipelines = [
774
+ {'type': 'agent', 'name': p.name, 'pipeline_id': p.id, 'policy_id': p.policy_id,
775
+ 'policy_name': p.policy.name, 'managed_by': p.managed_by,
776
+ 'last_modified': p.last_updated.isoformat()}
777
+ for p in agent_pipelines
778
+ ]
779
+ cpm_pipelines, unreachable = _list_cpm_pipelines()
780
+ return pipelines + cpm_pipelines, unreachable
781
+
782
+
783
+ def _list_cpm_pipelines():
784
+ """List the CPM pipelines on every CENTRALIZED connection.
785
+
786
+ Connections are queried in parallel with a short timeout, so one
787
+ unreachable cluster delays the search by at most ``_FIND_ES_TIMEOUT``.
788
+
789
+ Returns:
790
+ tuple: ``(pipelines, unreachable)``, both lists of dicts in the
791
+ :func:`pipeline_find` response form.
792
+ """
793
+ clients, unreachable = [], []
794
+ connections = Connection.objects.filter(
795
+ connection_type=Connection.ConnectionType.CENTRALIZED,
796
+ ).order_by('name')
797
+ for conn in connections:
798
+ try:
799
+ es = get_elastic_connection(conn.id).options(request_timeout=_FIND_ES_TIMEOUT)
800
+ except Exception as exc:
801
+ unreachable.append({'connection_id': conn.id, 'connection_name': conn.name,
802
+ 'error': str(exc)})
803
+ continue
804
+ clients.append((conn, es))
805
+
806
+ def fetch(client):
807
+ conn, es = client
808
+ try:
809
+ return conn, es.logstash.get_pipeline() or {}, None
810
+ except Exception as exc:
811
+ return conn, None, exc
812
+
813
+ pipelines = []
814
+ if clients:
815
+ with ThreadPoolExecutor(max_workers=min(len(clients), 8)) as pool:
816
+ for conn, raw, exc in pool.map(fetch, clients):
817
+ if exc is not None:
818
+ logger.warning("API find: CPM list failed (conn %s): %s", conn.id, exc)
819
+ unreachable.append({'connection_id': conn.id, 'connection_name': conn.name,
820
+ 'error': str(exc)})
821
+ continue
822
+ pipelines += [
823
+ {'type': 'cpm', 'name': name, 'connection_id': conn.id,
824
+ 'connection_name': conn.name,
825
+ 'last_modified': (raw[name] or {}).get('last_modified', '')}
826
+ for name in sorted(raw)
827
+ ]
828
+ return pipelines, unreachable
829
+
830
+
831
+ def _similar_pipelines(name, candidates, limit=10):
832
+ """Return pipelines whose names are close to, contain, or are contained in ``name``.
833
+
834
+ Args:
835
+ name: The name searched for.
836
+ candidates: Pipelines in :func:`pipeline_find` entry form.
837
+ limit: Maximum number to return.
838
+
839
+ Returns:
840
+ list: Up to ``limit`` candidates not named exactly ``name``, closest first.
841
+
842
+ Examples:
843
+ >>> [p['name'] for p in _similar_pipelines('asa-fixed', [
844
+ ... {'name': 'asa-new-fixed'}, {'name': 'asa'}, {'name': 'syslog'}])]
845
+ ['asa-new-fixed', 'asa']
846
+ """
847
+ wanted = name.lower()
848
+ names = {c['name'] for c in candidates if c['name'] != name}
849
+ close = set(difflib.get_close_matches(name, names, n=limit, cutoff=0.6))
850
+ close |= {n for n in names if wanted in n.lower() or n.lower() in wanted}
851
+
852
+ def closeness(candidate):
853
+ return difflib.SequenceMatcher(None, wanted, candidate['name'].lower()).ratio()
854
+
855
+ return sorted((c for c in candidates if c['name'] in close), key=closeness, reverse=True)[:limit]
856
+
857
+
858
+ # ---------------------------------------------------------------------------
859
+ # POST /api/pipelines/simulate/ — synchronous simulation
860
+ # ---------------------------------------------------------------------------
861
+
862
+ @csrf_exempt
863
+ @api_require_admin
864
+ def pipeline_simulate(request):
865
+ """Run a pipeline simulation synchronously and return results.
866
+
867
+ POST /api/pipelines/simulate/
868
+
869
+ Body fields (exactly one LSCL source: ``lscl``, ``pipeline_id``, or
870
+ ``connection_id`` + ``name``):
871
+ lscl (str): Raw Logstash config.
872
+ pipeline_id (int): Load LSCL from a saved agent pipeline.
873
+ connection_id (int): CENTRALIZED connection holding a CPM pipeline.
874
+ name (str): CPM pipeline ID to load LSCL from; requires ``connection_id``.
875
+ event (str): Sample log line or JSON to process. Mutually exclusive
876
+ with ``events``.
877
+ events (list): Bulk mode. Up to 100 log lines (str) or JSON events
878
+ (str or object), run on one simulation slot. Mutually exclusive
879
+ with ``event``.
880
+ sim_connection_id (int, optional): Specific simulate-agent connection.
881
+ policy_id (int, optional): Source policy for keystore sync.
882
+ timeout (int, optional): Max seconds to wait for all results once the
883
+ simulation slot is ready. Default 30, max 180.
884
+ detail (str, optional): ``full`` (default; raw ``results`` with every
885
+ filter snapshot), ``steps`` (``final`` event plus per-filter
886
+ ``steps`` listing only fields added, changed, or removed), or
887
+ ``final`` (``final`` event only). See ``API.simulation_detail``.
888
+
889
+ Returns:
890
+ Single mode: JSON with ``complete``, ``elapsed_ms``, ``slot_id``,
891
+ ``run_id``, ``detail``, and the fields for that detail level.
892
+
893
+ Bulk mode: JSON with ``events`` (one entry per input, in order, each
894
+ with ``index``, ``run_id``, ``complete``, the detail fields, and
895
+ ``error`` on failure), ``count``, ``complete_count``, ``slot_id``, and
896
+ ``elapsed_ms``.
897
+
898
+ Examples:
899
+ POST /api/pipelines/simulate/
900
+ {"pipeline_id": 12, "events": ["<164>%ASA-4-106023: Deny tcp ...",
901
+ {"message": "second event"}]}
902
+
903
+ POST /api/pipelines/simulate/
904
+ {"connection_id": 17, "name": "asa-new", "event": "<164>%ASA-4-106023: ..."}
905
+ """
906
+ if request.method != 'POST':
907
+ return JsonResponse({'success': False, 'error': 'Method not allowed'}, status=405)
908
+
909
+ data = parse_request_body(request)
910
+
911
+ # --- Resolve LSCL ---
912
+ lscl = (data.get('lscl') or '').strip()
913
+ pipeline_id = data.get('pipeline_id')
914
+ event_text = (data.get('event') or '').strip()
915
+ bulk_events = data.get('events')
916
+
917
+ if bulk_events is not None:
918
+ if event_text:
919
+ return JsonResponse(
920
+ {'success': False, 'error': 'Provide event or events, not both.'}, status=400,
921
+ )
922
+ if not isinstance(bulk_events, list) or not bulk_events:
923
+ return JsonResponse(
924
+ {'success': False, 'error': 'events must be a non-empty list.'}, status=400,
925
+ )
926
+ if len(bulk_events) > _SIMULATE_MAX_EVENTS:
927
+ return JsonResponse(
928
+ {'success': False, 'error': f'events is limited to {_SIMULATE_MAX_EVENTS} items.'},
929
+ status=400,
930
+ )
931
+ try:
932
+ bulk_events = [_event_to_text(e) for e in bulk_events]
933
+ except ValueError as exc:
934
+ return JsonResponse({'success': False, 'error': str(exc)}, status=400)
935
+
936
+ connection_id = data.get('connection_id')
937
+ cpm_name = (data.get('name') or '').strip()
938
+ if bool(connection_id) != bool(cpm_name):
939
+ return JsonResponse(
940
+ {'success': False, 'error': 'connection_id and name must be provided together.'},
941
+ status=400,
942
+ )
943
+
944
+ if sum(bool(s) for s in (lscl, pipeline_id, cpm_name)) > 1:
945
+ return JsonResponse(
946
+ {'success': False,
947
+ 'error': 'Provide only one of lscl, pipeline_id, or connection_id + name.'},
948
+ status=400,
949
+ )
950
+
951
+ if pipeline_id:
952
+ try:
953
+ p = Pipeline.objects.get(pk=pipeline_id)
954
+ lscl = p.lscl or ''
955
+ except Pipeline.DoesNotExist:
956
+ return JsonResponse({'success': False, 'error': 'pipeline_id not found.'}, status=404)
957
+
958
+ if cpm_name:
959
+ early = _check_centralized_connection_exists(connection_id)
960
+ if early:
961
+ return early
962
+ try:
963
+ raw = get_elastic_connection(connection_id).logstash.get_pipeline(id=cpm_name)
964
+ except Exception as exc:
965
+ if '404' in str(exc) or 'not found' in str(exc).lower():
966
+ raw = {}
967
+ else:
968
+ logger.error("API simulate: CPM fetch '%s' (conn %s): %s", cpm_name, connection_id, exc)
969
+ return JsonResponse({'success': False, 'error': str(exc)}, status=502)
970
+ if cpm_name not in (raw or {}):
971
+ return JsonResponse(
972
+ {'success': False,
973
+ 'error': f"CPM pipeline '{cpm_name}' not found on connection {connection_id}."},
974
+ status=404,
975
+ )
976
+ lscl = raw[cpm_name].get('pipeline', '')
977
+
978
+ if not lscl:
979
+ return JsonResponse(
980
+ {'success': False, 'error': 'lscl, pipeline_id, or connection_id + name is required.'},
981
+ status=400,
982
+ )
983
+ if not event_text and bulk_events is None:
984
+ return JsonResponse({'success': False, 'error': 'event or events is required.'}, status=400)
985
+
986
+ # --- Timeout ---
987
+ try:
988
+ timeout = min(int(data.get('timeout', _SIMULATE_DEFAULT_TIMEOUT)), _SIMULATE_MAX_TIMEOUT)
989
+ except (ValueError, TypeError):
990
+ timeout = _SIMULATE_DEFAULT_TIMEOUT
991
+
992
+ detail = data.get('detail') or 'full'
993
+ if detail not in DETAIL_LEVELS:
994
+ return JsonResponse(
995
+ {'success': False, 'error': f"detail must be one of: {', '.join(DETAIL_LEVELS)}."},
996
+ status=400,
997
+ )
998
+
999
+ # --- Convert LSCL → components ---
1000
+ try:
1001
+ raw_components = logstash_config_parse.logstash_config_to_components(lscl)
1002
+ # logstash_config_to_components returns a JSON string
1003
+ if isinstance(raw_components, str):
1004
+ components = json.loads(raw_components)
1005
+ else:
1006
+ components = raw_components
1007
+ except Exception as exc:
1008
+ logger.error("API simulate: LSCL parse error: %s", exc)
1009
+ return JsonResponse({'success': False, 'error': f'LSCL parse error: {exc}'}, status=400)
1010
+
1011
+ filter_plugins = components.get('filter', [])
1012
+ if not filter_plugins:
1013
+ return JsonResponse(
1014
+ {'success': False, 'error': 'Pipeline has no filter plugins to simulate.'},
1015
+ status=400,
1016
+ )
1017
+
1018
+ index = component_index(components)
1019
+
1020
+ def shape(results):
1021
+ return {'detail': detail, **shape_results(results, detail, index)}
1022
+
1023
+ t_start = time.time()
1024
+
1025
+ if bulk_events is not None:
1026
+ return _simulate_bulk(request, data, components, bulk_events, t_start, timeout, shape)
1027
+
1028
+ start = _start_simulation(request, data, components, event_text)
1029
+ if start.error:
1030
+ return JsonResponse(
1031
+ {'success': False, 'error': start.error, 'slot_id': start.slot_id}, status=502,
1032
+ )
1033
+ effective_run_id, slot_id = start.run_id, start.slot_id
1034
+
1035
+ # Slot allocation can take minutes on a cold agent; the timeout covers the wait for results.
1036
+ results = _collect_simulation_results([effective_run_id], time.time() + timeout)[effective_run_id]
1037
+ elapsed_ms = int((time.time() - t_start) * 1000)
1038
+
1039
+ if not results and start.forward_error:
1040
+ return JsonResponse(
1041
+ {
1042
+ 'success': False,
1043
+ 'error': f'Sending the event to the simulate agent failed: {start.forward_error}',
1044
+ 'run_id': effective_run_id,
1045
+ 'slot_id': slot_id,
1046
+ 'elapsed_ms': elapsed_ms,
1047
+ },
1048
+ status=502,
1049
+ )
1050
+ if not results:
1051
+ return JsonResponse(
1052
+ {
1053
+ 'success': False,
1054
+ 'error': (
1055
+ f'No simulation results within {timeout}s. The simulate agent may still be '
1056
+ 'loading the pipeline; retry once. If it times out again, the simulate '
1057
+ 'agent is not returning results.'
1058
+ ),
1059
+ 'run_id': effective_run_id,
1060
+ 'slot_id': slot_id,
1061
+ 'elapsed_ms': elapsed_ms,
1062
+ },
1063
+ status=408,
1064
+ )
1065
+
1066
+ logger.info(
1067
+ "API simulate: run_id=%s returned %d event(s) in %dms.",
1068
+ effective_run_id, len(results), elapsed_ms,
1069
+ )
1070
+ body = {
1071
+ 'success': True,
1072
+ 'run_id': effective_run_id,
1073
+ 'slot_id': slot_id,
1074
+ 'complete': run_status(results) != 'pending',
1075
+ 'elapsed_ms': elapsed_ms,
1076
+ **shape(results),
1077
+ }
1078
+ if detail == 'full':
1079
+ body['count'] = len(results)
1080
+ return JsonResponse(body)
1081
+
1082
+
1083
+ def _event_to_text(event):
1084
+ """Normalize one bulk ``events`` item to the text a simulation event is sent as.
1085
+
1086
+ Args:
1087
+ event: A log line (str) or a JSON event (dict).
1088
+
1089
+ Returns:
1090
+ str: The stripped log line, or the dict serialized as JSON.
1091
+
1092
+ Raises:
1093
+ ValueError: If the item is empty or not a str/dict.
1094
+
1095
+ Examples:
1096
+ >>> _event_to_text({"message": "hi"})
1097
+ '{"message": "hi"}'
1098
+ """
1099
+ if isinstance(event, dict):
1100
+ return json.dumps(event)
1101
+ if isinstance(event, str) and event.strip():
1102
+ return event.strip()
1103
+ raise ValueError('Each item in events must be a non-empty string or a JSON object.')
1104
+
1105
+
1106
+ def _start_simulation(request, data, components, event_text):
1107
+ """Instrument the pipeline, get a slot, and send the first event.
1108
+
1109
+ Args:
1110
+ request: The API request; its base URL receives the agent's results.
1111
+ data: Parsed API body (``policy_id`` / ``sim_connection_id`` honoured).
1112
+ components: Parsed pipeline components.
1113
+ event_text: Log line or JSON text for the event.
1114
+
1115
+ Returns:
1116
+ SimulationStart: ``error`` is set if the run did not start.
1117
+ """
1118
+ return start_simulation(
1119
+ components,
1120
+ event_text,
1121
+ ui_base_url=request.build_absolute_uri('/').rstrip('/'),
1122
+ # The API is stateless; don't persist a sticky agent on the caller's session.
1123
+ session={},
1124
+ sim_connection_id=data.get('sim_connection_id'),
1125
+ policy_id=data.get('policy_id'),
1126
+ )
1127
+
1128
+
1129
+ def _collect_simulation_results(run_ids, deadline):
1130
+ """Read results for ``run_ids`` until every run completes or ``deadline`` passes.
1131
+
1132
+ The step-0 "original" event arrives first; a run is done once its final
1133
+ event arrives (see :func:`~API.simulation_detail.run_status`). A final
1134
+ event without snapshots counts after a short grace, as in the editor, in
1135
+ case a later one carries them.
1136
+
1137
+ Args:
1138
+ run_ids: Run ids to wait for.
1139
+ deadline: ``time.time()`` value after which to stop waiting.
1140
+
1141
+ Returns:
1142
+ dict: ``{run_id: [result, ...]}`` for every requested run id.
1143
+ """
1144
+ collected = {run_id: [] for run_id in run_ids}
1145
+ grace_until = {}
1146
+ while True:
1147
+ pending = []
1148
+ for run_id, results in collected.items():
1149
+ status = run_status(results)
1150
+ if status == 'done':
1151
+ continue
1152
+ if status == 'empty_final':
1153
+ until = grace_until.setdefault(run_id, time.time() + _EMPTY_FINAL_GRACE)
1154
+ if time.time() >= until:
1155
+ continue
1156
+ pending.append(run_id)
1157
+ if not pending:
1158
+ break
1159
+ try:
1160
+ taken = SimulationResult.take(pending)
1161
+ except OperationalError as exc:
1162
+ # take() rolled back, so the rows are still queued for the next tick.
1163
+ logger.warning("API simulate: could not read results this tick: %s", exc)
1164
+ taken = {}
1165
+ for run_id, results in taken.items():
1166
+ collected[run_id].extend(results)
1167
+ if time.time() >= deadline:
1168
+ break
1169
+ time.sleep(0.25)
1170
+ return collected
1171
+
1172
+
1173
+ def _simulate_bulk(request, data, components, events, t_start, timeout, shape):
1174
+ """Run ``events`` on one simulation slot and return per-event results.
1175
+
1176
+ The first event allocates the slot; the rest are sent straight into it,
1177
+ skipping the slot checks and keystore sync that only the first needs.
1178
+ All runs share one ``timeout``, counted from when the slot is ready.
1179
+ ``shape`` turns one run's raw results
1180
+ into its response fields.
1181
+ """
1182
+ start = _start_simulation(request, data, components, events[0])
1183
+ if start.error:
1184
+ # Slot allocation failed; later events would fail the same way.
1185
+ return JsonResponse(
1186
+ {'success': False, 'error': start.error, 'slot_id': start.slot_id}, status=502,
1187
+ )
1188
+ slot_id = start.slot_id
1189
+ wait_start = time.time()
1190
+ entries = [{'index': 0, 'run_id': start.run_id, 'error': start.forward_error}]
1191
+ for index, event_text in enumerate(events[1:], start=1):
1192
+ run_id = new_run_id()
1193
+ _queued, forward_error = send_simulation_event(
1194
+ start.agent_url, slot_id, run_id, event_text, agent_headers=start.agent_headers,
1195
+ )
1196
+ entries.append({'index': index, 'run_id': run_id, 'error': forward_error})
1197
+
1198
+ pending = [e['run_id'] for e in entries]
1199
+ collected = _collect_simulation_results(pending, wait_start + timeout)
1200
+ elapsed_ms = int((time.time() - t_start) * 1000)
1201
+
1202
+ complete_count = 0
1203
+ for entry in entries:
1204
+ results = collected.get(entry['run_id'], [])
1205
+ entry['complete'] = run_status(results) != 'pending'
1206
+ complete_count += entry['complete']
1207
+ # A send error only matters if the agent never delivered results.
1208
+ forward_error = entry.pop('error')
1209
+ if not entry['complete']:
1210
+ entry['error'] = forward_error or f'Timed out after {timeout}s.'
1211
+ entry.update(shape(results))
1212
+
1213
+ logger.info(
1214
+ "API simulate bulk: slot=%s %d/%d event(s) complete in %dms.",
1215
+ slot_id, complete_count, len(entries), elapsed_ms,
1216
+ )
1217
+ return JsonResponse({
1218
+ 'success': complete_count > 0,
1219
+ 'slot_id': slot_id,
1220
+ 'events': entries,
1221
+ 'count': len(entries),
1222
+ 'complete_count': complete_count,
1223
+ 'elapsed_ms': elapsed_ms,
1224
+ }, status=200 if complete_count else 408)