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/snmp_views.py ADDED
@@ -0,0 +1,1539 @@
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 SNMP resources.
6
+
7
+ Devices
8
+ -------
9
+ GET /api/snmp/devices/ device_list (any authenticated user)
10
+ POST /api/snmp/devices/ device_list (admin)
11
+ GET /api/snmp/devices/{id}/ device_detail (any authenticated user)
12
+ PUT /api/snmp/devices/{id}/ device_detail (admin)
13
+ DELETE /api/snmp/devices/{id}/ device_detail (admin)
14
+
15
+ Credentials
16
+ -----------
17
+ GET /api/snmp/credentials/ credential_list (any authenticated user)
18
+ POST /api/snmp/credentials/ credential_list (admin)
19
+ GET /api/snmp/credentials/{id}/ credential_detail (any authenticated user)
20
+ PUT /api/snmp/credentials/{id}/ credential_detail (admin)
21
+ DELETE /api/snmp/credentials/{id}/ credential_detail (admin)
22
+
23
+ Networks
24
+ --------
25
+ GET /api/snmp/networks/ network_list (any authenticated user)
26
+ POST /api/snmp/networks/ network_list (admin)
27
+ GET /api/snmp/networks/{id}/ network_detail (any authenticated user)
28
+ PUT /api/snmp/networks/{id}/ network_detail (admin)
29
+ DELETE /api/snmp/networks/{id}/ network_detail (admin)
30
+
31
+ Profiles (OID device profiles)
32
+ -------------------------------
33
+ GET /api/snmp/profiles/ profile_list (any authenticated user)
34
+ POST /api/snmp/profiles/ profile_list (admin)
35
+ GET /api/snmp/profiles/{id}/ profile_detail (any authenticated user)
36
+ PUT /api/snmp/profiles/{id}/ profile_detail (admin)
37
+ DELETE /api/snmp/profiles/{id}/ profile_detail (admin)
38
+
39
+ Device Templates
40
+ ----------------
41
+ GET /api/snmp/templates/ template_list (any authenticated user)
42
+ POST /api/snmp/templates/ template_list (admin)
43
+ GET /api/snmp/templates/{id}/ template_detail (any authenticated user)
44
+ PUT /api/snmp/templates/{id}/ template_detail (admin)
45
+ DELETE /api/snmp/templates/{id}/ template_detail (admin)
46
+ """
47
+
48
+ import json
49
+ import logging
50
+ import re
51
+ from decimal import Decimal, InvalidOperation
52
+
53
+ from django.core.exceptions import ValidationError
54
+ from django.db import IntegrityError
55
+ from django.db.models import Q
56
+ from django.http import JsonResponse
57
+ from django.views.decorators.csrf import csrf_exempt
58
+
59
+ from SNMP.models import Credential, Device, DeviceTemplate, Network, Profile, SNMPDeploymentState
60
+ from Common.elastic_utils import get_elastic_connection
61
+ from Common.formatters import _sanitize_pipeline_name_component
62
+ from Common.validators import validate_namespace
63
+
64
+ from API.auth import api_require_auth, api_require_admin, parse_request_body, protected_response
65
+
66
+ logger = logging.getLogger(__name__)
67
+
68
+ _VALID_SORT_FIELDS = frozenset([
69
+ 'name', '-name',
70
+ 'ip_address', '-ip_address',
71
+ 'hostname', '-hostname',
72
+ 'created_at', '-created_at',
73
+ ])
74
+
75
+
76
+ # ---------------------------------------------------------------------------
77
+ # Serialization helpers
78
+ # ---------------------------------------------------------------------------
79
+
80
+ def _device_list_data(device):
81
+ """Serialize a Device for the list response (no metadata/location coords)."""
82
+ return {
83
+ 'id': device.id,
84
+ 'name': device.name,
85
+ 'ip_address': device.ip_address,
86
+ 'hostname': device.hostname,
87
+ 'port': device.port,
88
+ 'retries': device.retries,
89
+ 'timeout': device.timeout,
90
+ 'credential_id': device.credential.id if device.credential else None,
91
+ 'credential_name': device.credential.name if device.credential else None,
92
+ 'network_id': device.network.id if device.network else None,
93
+ 'network_name': device.network.name if device.network else None,
94
+ 'network_deployment_mode': device.network.deployment_mode if device.network else None,
95
+ 'device_template_id': device.device_template.id if device.device_template else None,
96
+ 'device_template_name': device.device_template.name if device.device_template else None,
97
+ 'site': device.site,
98
+ 'building': device.building,
99
+ 'room': device.room,
100
+ 'created_at': device.created_at.isoformat(),
101
+ }
102
+
103
+
104
+ def _device_detail_data(device):
105
+ """Serialize a Device for a single-item response (full fields)."""
106
+ return {
107
+ 'id': device.id,
108
+ 'name': device.name,
109
+ 'ip_address': device.ip_address,
110
+ 'hostname': device.hostname,
111
+ 'port': device.port,
112
+ 'retries': device.retries,
113
+ 'timeout': device.timeout,
114
+ 'credential_id': device.credential_id,
115
+ 'network_id': device.network_id,
116
+ 'device_template_id': device.device_template_id,
117
+ 'site': device.site,
118
+ 'building': device.building,
119
+ 'room': device.room,
120
+ 'latitude': float(device.latitude) if device.latitude is not None else None,
121
+ 'longitude': float(device.longitude) if device.longitude is not None else None,
122
+ 'metadata': device.metadata,
123
+ 'created_at': device.created_at.isoformat(),
124
+ 'updated_at': device.updated_at.isoformat(),
125
+ }
126
+
127
+
128
+ # ---------------------------------------------------------------------------
129
+ # Request parsing helpers
130
+ # ---------------------------------------------------------------------------
131
+
132
+ def _parse_device_fields(data, device):
133
+ """Apply a parsed JSON body onto a Device instance.
134
+
135
+ Mutates ``device`` in place. Raises ``ValueError`` for bad numeric inputs.
136
+
137
+ Args:
138
+ data: dict from ``parse_request_body``.
139
+ device: ``Device`` instance to update (may be unsaved).
140
+ """
141
+ if 'name' in data:
142
+ new_name = (data['name'] or '').strip()
143
+ # L3 fix: an empty name on update was silently ignored; now raise so the
144
+ # caller returns 400.
145
+ if not new_name:
146
+ raise ValueError('name cannot be empty.')
147
+ device.name = new_name
148
+
149
+ # H13 fix: ip_address/hostname were unconditionally overwritten from data,
150
+ # so a partial PUT that omitted either field would silently null it out.
151
+ if 'ip_address' in data:
152
+ device.ip_address = data['ip_address'] or None
153
+ if 'hostname' in data:
154
+ device.hostname = data['hostname'] or None
155
+
156
+ if 'port' in data and data['port'] is not None:
157
+ device.port = int(data['port'])
158
+ if 'retries' in data and data['retries'] is not None:
159
+ device.retries = int(data['retries'])
160
+ if 'timeout' in data and data['timeout'] is not None:
161
+ device.timeout = int(data['timeout'])
162
+
163
+ # FK ids — explicit None clears the relationship
164
+ if 'credential' in data:
165
+ device.credential_id = data['credential']
166
+ if 'network' in data:
167
+ device.network_id = data['network']
168
+ if 'device_template' in data:
169
+ device.device_template_id = data['device_template']
170
+
171
+ # Location
172
+ if 'site' in data:
173
+ device.site = data['site'] or None
174
+ if 'building' in data:
175
+ device.building = data['building'] or None
176
+ if 'room' in data:
177
+ device.room = data['room'] or None
178
+
179
+ lat = data.get('latitude')
180
+ lon = data.get('longitude')
181
+ try:
182
+ device.latitude = Decimal(str(round(float(lat), 6))) if lat is not None else None
183
+ device.longitude = Decimal(str(round(float(lon), 6))) if lon is not None else None
184
+ except (InvalidOperation, ValueError, TypeError) as exc:
185
+ raise ValueError(f'Invalid lat/lon value: {exc}') from exc
186
+
187
+ # Metadata
188
+ raw_meta = data.get('metadata')
189
+ if raw_meta is not None:
190
+ if isinstance(raw_meta, str):
191
+ try:
192
+ device.metadata = json.loads(raw_meta)
193
+ except (json.JSONDecodeError, ValueError):
194
+ device.metadata = {}
195
+ elif isinstance(raw_meta, dict):
196
+ device.metadata = raw_meta
197
+ else:
198
+ device.metadata = {}
199
+
200
+
201
+ # ---------------------------------------------------------------------------
202
+ # /api/snmp/devices/ — list + create
203
+ # ---------------------------------------------------------------------------
204
+
205
+ @csrf_exempt
206
+ def device_list(request):
207
+ """List all SNMP devices or create a new one.
208
+
209
+ GET /api/snmp/devices/
210
+ Paginated, filterable list. Any authenticated user.
211
+
212
+ POST /api/snmp/devices/
213
+ Create a device from a JSON body. Admin only.
214
+ Calls ``SNMPDeploymentState.mark_config_changed()`` on success.
215
+ """
216
+ if request.method == 'GET':
217
+ return _list_devices(request)
218
+ if request.method == 'POST':
219
+ return _create_device(request)
220
+ return JsonResponse({'error': 'Method not allowed'}, status=405)
221
+
222
+
223
+ @api_require_auth
224
+ def _list_devices(request):
225
+ # H3 fix: non-integer page/page_size raised ValueError, crashing as 500.
226
+ try:
227
+ page = max(1, int(request.GET.get('page', 1)))
228
+ page_size = max(1, min(200, int(request.GET.get('page_size', 25))))
229
+ except (ValueError, TypeError):
230
+ return JsonResponse({'success': False, 'error': 'page and page_size must be positive integers.'}, status=400)
231
+ search = request.GET.get('search', '').strip()
232
+ network_filter = request.GET.get('network', '').strip()
233
+ sort_by = request.GET.get('sort_by', '-created_at')
234
+
235
+ if sort_by not in _VALID_SORT_FIELDS:
236
+ sort_by = '-created_at'
237
+
238
+ qs = Device.objects.select_related('credential', 'network', 'device_template').only(
239
+ 'id', 'name', 'ip_address', 'hostname', 'port', 'retries', 'timeout', 'created_at',
240
+ 'site', 'building', 'room',
241
+ 'credential__id', 'credential__name',
242
+ 'network__id', 'network__name', 'network__deployment_mode',
243
+ 'device_template__id', 'device_template__name',
244
+ )
245
+
246
+ if search:
247
+ qs = qs.filter(
248
+ Q(name__icontains=search) |
249
+ Q(ip_address__icontains=search) |
250
+ Q(hostname__icontains=search)
251
+ )
252
+ if network_filter:
253
+ try:
254
+ qs = qs.filter(network_id=int(network_filter))
255
+ except (ValueError, TypeError):
256
+ return JsonResponse({'success': False, 'error': 'network filter must be an integer id.'}, status=400)
257
+
258
+ qs = qs.order_by(sort_by)
259
+
260
+ total = qs.count()
261
+ offset = (page - 1) * page_size
262
+ page_qs = list(qs[offset:offset + page_size + 1])
263
+ has_next = len(page_qs) > page_size
264
+ devices_page = page_qs[:page_size]
265
+ total_pages = max(1, (total + page_size - 1) // page_size)
266
+
267
+ return JsonResponse({
268
+ 'devices': [_device_list_data(d) for d in devices_page],
269
+ 'total': total,
270
+ 'page': page,
271
+ 'page_size': page_size,
272
+ 'total_pages': total_pages,
273
+ 'has_next': has_next,
274
+ 'has_previous': page > 1,
275
+ })
276
+
277
+
278
+ @api_require_admin
279
+ def _create_device(request):
280
+ data = parse_request_body(request)
281
+
282
+ name = (data.get('name') or '').strip()
283
+ if not name:
284
+ return JsonResponse({'success': False, 'error': 'name is required.'}, status=400)
285
+
286
+ device = Device(
287
+ port=161,
288
+ retries=2,
289
+ timeout=1000,
290
+ metadata={},
291
+ )
292
+ device.name = name
293
+
294
+ try:
295
+ _parse_device_fields(data, device)
296
+ except (ValueError, TypeError) as exc:
297
+ return JsonResponse({'success': False, 'error': f'Invalid numeric field: {exc}'}, status=400)
298
+
299
+ try:
300
+ device.save()
301
+ except ValidationError as exc:
302
+ errors = exc.message_dict if hasattr(exc, 'message_dict') else {'error': exc.messages}
303
+ return JsonResponse({'success': False, 'error': errors}, status=400)
304
+ except IntegrityError as exc:
305
+ return JsonResponse({'success': False, 'error': str(exc)}, status=409)
306
+ except Exception as exc:
307
+ logger.error("API create device: %s", exc)
308
+ return JsonResponse({'success': False, 'error': 'An internal error occurred. Check server logs.'}, status=500)
309
+
310
+ SNMPDeploymentState.mark_config_changed()
311
+ logger.info("API: device '%s' (ID: %s) created by %s.", name, device.id, request.user.username)
312
+ return JsonResponse({
313
+ 'success': True,
314
+ 'id': device.id,
315
+ 'message': 'Device created successfully.',
316
+ }, status=201)
317
+
318
+
319
+ # ---------------------------------------------------------------------------
320
+ # /api/snmp/devices/{id}/ — read, update, delete
321
+ # ---------------------------------------------------------------------------
322
+
323
+ @csrf_exempt
324
+ def device_detail(request, device_id):
325
+ """Read, update, or delete a single SNMP device.
326
+
327
+ GET /api/snmp/devices/{id}/ any authenticated user
328
+ PUT /api/snmp/devices/{id}/ admin only
329
+ DELETE /api/snmp/devices/{id}/ admin only
330
+ """
331
+ if request.method == 'GET':
332
+ return _get_device(request, device_id)
333
+ if request.method == 'PUT':
334
+ return _update_device(request, device_id)
335
+ if request.method == 'DELETE':
336
+ return _delete_device(request, device_id)
337
+ return JsonResponse({'error': 'Method not allowed'}, status=405)
338
+
339
+
340
+ @api_require_auth
341
+ def _get_device(request, device_id):
342
+ try:
343
+ device = Device.objects.get(pk=device_id)
344
+ except Device.DoesNotExist:
345
+ return JsonResponse({'success': False, 'error': 'Device not found.'}, status=404)
346
+ return JsonResponse({'success': True, 'device': _device_detail_data(device)})
347
+
348
+
349
+ @api_require_admin
350
+ def _update_device(request, device_id):
351
+ try:
352
+ device = Device.objects.get(pk=device_id)
353
+ except Device.DoesNotExist:
354
+ return JsonResponse({'success': False, 'error': 'Device not found.'}, status=404)
355
+
356
+ data = parse_request_body(request)
357
+
358
+ try:
359
+ _parse_device_fields(data, device)
360
+ except (ValueError, TypeError) as exc:
361
+ return JsonResponse({'success': False, 'error': f'Invalid numeric field: {exc}'}, status=400)
362
+
363
+ try:
364
+ device.save()
365
+ except ValidationError as exc:
366
+ errors = exc.message_dict if hasattr(exc, 'message_dict') else {'error': exc.messages}
367
+ return JsonResponse({'success': False, 'error': errors}, status=400)
368
+ except IntegrityError as exc:
369
+ return JsonResponse({'success': False, 'error': str(exc)}, status=409)
370
+ except Exception as exc:
371
+ logger.error("API update device %s: %s", device_id, exc)
372
+ return JsonResponse({'success': False, 'error': 'An internal error occurred. Check server logs.'}, status=500)
373
+
374
+ SNMPDeploymentState.mark_config_changed()
375
+ logger.info("API: device %s updated by %s.", device_id, request.user.username)
376
+ return JsonResponse({
377
+ 'success': True,
378
+ 'id': device.id,
379
+ 'message': 'Device updated successfully.',
380
+ })
381
+
382
+
383
+ @api_require_admin
384
+ def _delete_device(request, device_id):
385
+ try:
386
+ device = Device.objects.get(pk=device_id)
387
+ except Device.DoesNotExist:
388
+ return JsonResponse({'success': False, 'error': 'Device not found.'}, status=404)
389
+
390
+ name = device.name
391
+ device.delete()
392
+ SNMPDeploymentState.mark_config_changed()
393
+ logger.warning("API: device '%s' (ID: %s) deleted by %s.", name, device_id, request.user.username)
394
+ return JsonResponse({'success': True, 'message': f"Device '{name}' deleted."})
395
+
396
+
397
+ # ===========================================================================
398
+ # CREDENTIALS
399
+ # ===========================================================================
400
+
401
+ def _credential_safe_data(cred):
402
+ """Return a credential dict with secrets masked."""
403
+ data = {
404
+ 'id': cred.id,
405
+ 'name': cred.name,
406
+ 'description': cred.description,
407
+ 'version': cred.version,
408
+ 'created_at': cred.created_at.isoformat(),
409
+ 'updated_at': cred.updated_at.isoformat(),
410
+ }
411
+ if cred.version in ('1', '2c'):
412
+ data['has_community'] = bool(cred.community)
413
+ data['community'] = '***' if cred.community else ''
414
+ else:
415
+ data['security_name'] = cred.security_name or ''
416
+ data['security_level'] = cred.security_level or ''
417
+ data['auth_protocol'] = cred.auth_protocol or ''
418
+ data['priv_protocol'] = cred.priv_protocol or ''
419
+ data['has_auth_pass'] = bool(cred.auth_pass)
420
+ data['has_priv_pass'] = bool(cred.priv_pass)
421
+ data['auth_pass'] = '***' if cred.auth_pass else ''
422
+ data['priv_pass'] = '***' if cred.priv_pass else ''
423
+ return data
424
+
425
+
426
+ def _apply_credential_fields(data, cred, is_update=False):
427
+ """Apply JSON body fields to a Credential instance.
428
+
429
+ For updates, empty strings for secret fields keep the existing encrypted value.
430
+ """
431
+ if 'name' in data:
432
+ cred.name = (data['name'] or '').strip()
433
+ if 'description' in data:
434
+ cred.description = data.get('description', '') or ''
435
+ if 'version' in data:
436
+ cred.version = data['version']
437
+
438
+ version = cred.version
439
+ # Clear non-community version-specific fields before re-applying.
440
+ # H12 fix: community is NOT unconditionally cleared here; it is only written
441
+ # when 'community' is present in the request body (partial-update safety).
442
+ cred.security_name = ''
443
+ cred.security_level = ''
444
+ cred.auth_protocol = ''
445
+ cred.priv_protocol = ''
446
+ if not is_update:
447
+ cred.community = ''
448
+ cred.auth_pass = ''
449
+ cred.priv_pass = ''
450
+
451
+ if version in ('1', '2c'):
452
+ if 'community' in data:
453
+ # Explicit community update.
454
+ cred.community = data['community'] or 'public'
455
+ elif not is_update:
456
+ # New credential — apply the default.
457
+ cred.community = 'public'
458
+ # else: partial update without 'community' → keep the stored value.
459
+ elif version == '3':
460
+ cred.security_name = data.get('security_name', '') or ''
461
+ cred.security_level = data.get('security_level', '') or ''
462
+ if cred.security_level in ('authNoPriv', 'authPriv'):
463
+ cred.auth_protocol = data.get('auth_protocol', '') or ''
464
+ ap = data.get('auth_pass', '')
465
+ if ap: # empty string on update = keep existing
466
+ cred.auth_pass = ap
467
+ if cred.security_level == 'authPriv':
468
+ cred.priv_protocol = data.get('priv_protocol', '') or ''
469
+ pp = data.get('priv_pass', '')
470
+ if pp:
471
+ cred.priv_pass = pp
472
+ # H14 fix: downgrading to noAuthNoPriv must clear stale auth/priv passes
473
+ # that were set when the level was previously higher.
474
+ if cred.security_level == 'noAuthNoPriv':
475
+ cred.auth_pass = ''
476
+ cred.priv_pass = ''
477
+
478
+
479
+ @csrf_exempt
480
+ def credential_list(request):
481
+ """List all credentials or create a new one."""
482
+ if request.method == 'GET':
483
+ return _list_credentials(request)
484
+ if request.method == 'POST':
485
+ return _create_credential(request)
486
+ return JsonResponse({'error': 'Method not allowed'}, status=405)
487
+
488
+
489
+ @api_require_auth
490
+ def _list_credentials(request):
491
+ from django.db.models import Count
492
+ qs = Credential.objects.annotate(device_count=Count('devices')).order_by('name')
493
+
494
+ search = request.GET.get('search', '').strip()
495
+ if search:
496
+ qs = qs.filter(Q(name__icontains=search) | Q(description__icontains=search))
497
+
498
+ version_filter = request.GET.get('version', '').strip()
499
+ if version_filter:
500
+ qs = qs.filter(version=version_filter)
501
+
502
+ items = []
503
+ for cred in qs:
504
+ items.append({
505
+ 'id': cred.id,
506
+ 'name': cred.name,
507
+ 'description': cred.description,
508
+ 'version': cred.version,
509
+ 'security_level': cred.security_level or None,
510
+ 'device_count': cred.device_count,
511
+ 'created_at': cred.created_at.isoformat(),
512
+ })
513
+ return JsonResponse({'credentials': items, 'total': len(items)})
514
+
515
+
516
+ @api_require_admin
517
+ def _create_credential(request):
518
+ data = parse_request_body(request)
519
+ name = (data.get('name') or '').strip()
520
+ if not name:
521
+ return JsonResponse({'success': False, 'error': 'name is required.'}, status=400)
522
+ version = (data.get('version') or '').strip()
523
+ if version not in ('1', '2c', '3'):
524
+ return JsonResponse({'success': False, 'error': "version must be '1', '2c', or '3'."}, status=400)
525
+
526
+ cred = Credential(name=name, version=version)
527
+ _apply_credential_fields(data, cred, is_update=False)
528
+ try:
529
+ cred.save()
530
+ except ValidationError as exc:
531
+ errors = exc.message_dict if hasattr(exc, 'message_dict') else {'error': exc.messages}
532
+ return JsonResponse({'success': False, 'error': errors}, status=400)
533
+ except IntegrityError:
534
+ # H5 fix: a duplicate name race produces IntegrityError which was un-caught.
535
+ return JsonResponse({'success': False, 'error': f"A credential named '{name}' already exists."}, status=409)
536
+ except Exception as exc:
537
+ logger.error("API create credential: %s", exc)
538
+ return JsonResponse({'success': False, 'error': 'An internal error occurred. Check server logs.'}, status=500)
539
+
540
+ SNMPDeploymentState.mark_config_changed()
541
+ logger.info("API: credential '%s' (id=%s) created by %s.", name, cred.id, request.user.username)
542
+ return JsonResponse({'success': True, 'id': cred.id, 'message': 'Credential created successfully.'}, status=201)
543
+
544
+
545
+ @csrf_exempt
546
+ def credential_detail(request, credential_id):
547
+ """Read, update, or delete a single credential."""
548
+ if request.method == 'GET':
549
+ return _get_credential(request, credential_id)
550
+ if request.method == 'PUT':
551
+ return _update_credential(request, credential_id)
552
+ if request.method == 'DELETE':
553
+ return _delete_credential(request, credential_id)
554
+ return JsonResponse({'error': 'Method not allowed'}, status=405)
555
+
556
+
557
+ @api_require_auth
558
+ def _get_credential(request, credential_id):
559
+ try:
560
+ cred = Credential.objects.get(pk=credential_id)
561
+ except Credential.DoesNotExist:
562
+ return JsonResponse({'success': False, 'error': 'Credential not found.'}, status=404)
563
+ return JsonResponse({'success': True, 'credential': _credential_safe_data(cred)})
564
+
565
+
566
+ @api_require_admin
567
+ def _update_credential(request, credential_id):
568
+ try:
569
+ cred = Credential.objects.get(pk=credential_id)
570
+ except Credential.DoesNotExist:
571
+ return JsonResponse({'success': False, 'error': 'Credential not found.'}, status=404)
572
+
573
+ data = parse_request_body(request)
574
+ _apply_credential_fields(data, cred, is_update=True)
575
+ try:
576
+ cred.save()
577
+ except ValidationError as exc:
578
+ errors = exc.message_dict if hasattr(exc, 'message_dict') else {'error': exc.messages}
579
+ return JsonResponse({'success': False, 'error': errors}, status=400)
580
+ except IntegrityError:
581
+ # H6 fix: catch duplicate-name race on update.
582
+ return JsonResponse({'success': False, 'error': 'A credential with that name already exists.'}, status=409)
583
+ except Exception as exc:
584
+ logger.error("API update credential %s: %s", credential_id, exc)
585
+ return JsonResponse({'success': False, 'error': 'An internal error occurred. Check server logs.'}, status=500)
586
+
587
+ SNMPDeploymentState.mark_config_changed()
588
+ logger.info("API: credential %s updated by %s.", credential_id, request.user.username)
589
+ return JsonResponse({'success': True, 'id': cred.id, 'message': 'Credential updated successfully.'})
590
+
591
+
592
+ @api_require_admin
593
+ def _delete_credential(request, credential_id):
594
+ try:
595
+ cred = Credential.objects.get(pk=credential_id)
596
+ except Credential.DoesNotExist:
597
+ return JsonResponse({'success': False, 'error': 'Credential not found.'}, status=404)
598
+ name = cred.name
599
+ cred.delete()
600
+ SNMPDeploymentState.mark_config_changed()
601
+ logger.warning("API: credential '%s' (id=%s) deleted by %s.", name, credential_id, request.user.username)
602
+ return JsonResponse({'success': True, 'message': f"Credential '{name}' deleted."})
603
+
604
+
605
+ # ===========================================================================
606
+ # NETWORKS
607
+ # ===========================================================================
608
+
609
+ def _network_data(net, device_count=None):
610
+ return {
611
+ 'id': net.id,
612
+ 'name': net.name,
613
+ 'network_range': net.network_range,
614
+ 'deployment_mode': net.deployment_mode,
615
+ 'credential_mode': net.credential_mode,
616
+ 'connection_id': net.connection_id,
617
+ 'connection_name': net.connection.name if net.connection else None,
618
+ 'agent_connection_id': net.agent_connection_id,
619
+ 'agent_connection_name': net.agent_connection.name if net.agent_connection else None,
620
+ 'discovery_credential_id': net.discovery_credential_id,
621
+ 'credential_id': net.credential_id,
622
+ 'discovery_enabled': net.discovery_enabled,
623
+ 'traps_enabled': net.traps_enabled,
624
+ 'interval': net.interval,
625
+ 'namespace': net.namespace,
626
+ 'namespace_from_device_template': net.namespace_from_device_template,
627
+ 'ssl_certificate_authorities': net.ssl_certificate_authorities,
628
+ 'device_count': device_count,
629
+ 'created_at': net.created_at.isoformat(),
630
+ 'updated_at': net.updated_at.isoformat(),
631
+ }
632
+
633
+
634
+ def _ssl_certificate_authorities_value(raw):
635
+ """Normalize an API value to the stored comma-separated string.
636
+
637
+ Accepts a comma-separated string or a list of paths, so an API client that
638
+ sends a JSON array does not cause a 500.
639
+
640
+ Examples:
641
+ >>> _ssl_certificate_authorities_value(["/a.crt", "/b.crt"])
642
+ '/a.crt, /b.crt'
643
+ >>> _ssl_certificate_authorities_value(None)
644
+ ''
645
+ """
646
+ if isinstance(raw, (list, tuple)):
647
+ raw = ", ".join(str(p) for p in raw)
648
+ return (raw or '').strip()
649
+
650
+
651
+ def _validate_network_cidr(network_range):
652
+ """Return (ok, error_str). Rejects prefixes larger than /20."""
653
+ import ipaddress as _ip
654
+ if not (network_range or '').strip():
655
+ return False, 'network_range is required.'
656
+ try:
657
+ net = _ip.ip_network(network_range or '', strict=False)
658
+ if net.prefixlen < 20:
659
+ return False, (
660
+ f'Network range {network_range} is too large. '
661
+ 'Networks larger than /20 are not supported. '
662
+ 'Please break it into smaller subnets (/20 or smaller).'
663
+ )
664
+ except ValueError:
665
+ # M14 fix: previously this swallowed the ValueError so an invalid CIDR
666
+ # string reached the model and could produce a confusing DB error.
667
+ return False, f"'{network_range}' is not a valid CIDR network range."
668
+ return True, None
669
+
670
+
671
+ def _apply_network_fields(data, net):
672
+ """Apply JSON body onto a Network instance (create or update)."""
673
+ if 'name' in data:
674
+ net.name = (data['name'] or '').strip()
675
+ if 'network_range' in data:
676
+ net.network_range = data['network_range'] or net.network_range
677
+ if 'deployment_mode' in data:
678
+ net.deployment_mode = data['deployment_mode'] or 'CENTRALIZED'
679
+ if 'credential_mode' in data:
680
+ net.credential_mode = data['credential_mode'] or 'KEYSTORE'
681
+ if 'discovery_enabled' in data:
682
+ net.discovery_enabled = bool(data['discovery_enabled'])
683
+ if 'traps_enabled' in data:
684
+ net.traps_enabled = bool(data['traps_enabled'])
685
+ if 'interval' in data and data['interval'] is not None:
686
+ net.interval = int(data['interval'])
687
+ if 'namespace' in data:
688
+ net.namespace = data['namespace'] or 'default'
689
+ if 'namespace_from_device_template' in data:
690
+ net.namespace_from_device_template = bool(data['namespace_from_device_template'])
691
+ if 'ssl_certificate_authorities' in data:
692
+ net.ssl_certificate_authorities = _ssl_certificate_authorities_value(
693
+ data['ssl_certificate_authorities']
694
+ )
695
+
696
+ # FK fields — explicit None/null clears the relationship
697
+ for attr, field in (
698
+ ('connection', 'connection_id'),
699
+ ('agent_connection', 'agent_connection_id'),
700
+ ('discovery_credential', 'discovery_credential_id'),
701
+ ('credential', 'credential_id'),
702
+ ):
703
+ if attr in data:
704
+ setattr(net, field, data[attr]) # None clears, int id sets
705
+
706
+
707
+ @csrf_exempt
708
+ def network_list(request):
709
+ """List all networks or create a new one."""
710
+ if request.method == 'GET':
711
+ return _list_networks(request)
712
+ if request.method == 'POST':
713
+ return _create_network(request)
714
+ return JsonResponse({'error': 'Method not allowed'}, status=405)
715
+
716
+
717
+ @api_require_auth
718
+ def _list_networks(request):
719
+ from django.db.models import Count
720
+ qs = Network.objects.select_related('connection', 'agent_connection').annotate(
721
+ device_count=Count('devices')
722
+ ).order_by('name')
723
+
724
+ search = request.GET.get('search', '').strip()
725
+ if search:
726
+ qs = qs.filter(Q(name__icontains=search) | Q(network_range__icontains=search))
727
+
728
+ return JsonResponse({
729
+ 'networks': [_network_data(n, n.device_count) for n in qs],
730
+ 'total': qs.count(),
731
+ })
732
+
733
+
734
+ @api_require_admin
735
+ def _create_network(request):
736
+ data = parse_request_body(request)
737
+ name = (data.get('name') or '').strip()
738
+ if not name:
739
+ return JsonResponse({'success': False, 'error': 'name is required.'}, status=400)
740
+
741
+ network_range = data.get('network_range', '')
742
+ ok, err = _validate_network_cidr(network_range)
743
+ if not ok:
744
+ return JsonResponse({'success': False, 'error': err}, status=400)
745
+
746
+ namespace = data.get('namespace', 'default') or 'default'
747
+ use_template_ns = bool(data.get('namespace_from_device_template', False))
748
+ if not use_template_ns:
749
+ ns_valid, ns_error = validate_namespace(namespace)
750
+ if not ns_valid:
751
+ return JsonResponse({'success': False, 'error': ns_error}, status=400)
752
+
753
+ net = Network(
754
+ name=name,
755
+ network_range=network_range,
756
+ discovery_enabled=bool(data.get('discovery_enabled', True)),
757
+ traps_enabled=bool(data.get('traps_enabled', False)),
758
+ interval=int(data.get('interval', 30) or 30),
759
+ namespace=namespace,
760
+ namespace_from_device_template=use_template_ns,
761
+ deployment_mode=data.get('deployment_mode', 'CENTRALIZED') or 'CENTRALIZED',
762
+ credential_mode=data.get('credential_mode', 'KEYSTORE') or 'KEYSTORE',
763
+ ssl_certificate_authorities=_ssl_certificate_authorities_value(
764
+ data.get('ssl_certificate_authorities')
765
+ ),
766
+ )
767
+ for attr, field in (
768
+ ('connection', 'connection_id'),
769
+ ('agent_connection', 'agent_connection_id'),
770
+ ('discovery_credential', 'discovery_credential_id'),
771
+ ('credential', 'credential_id'),
772
+ ):
773
+ if data.get(attr) is not None:
774
+ setattr(net, field, data[attr])
775
+
776
+ try:
777
+ net.save()
778
+ except ValidationError as exc:
779
+ errors = exc.message_dict if hasattr(exc, 'message_dict') else {'error': exc.messages}
780
+ return JsonResponse({'success': False, 'error': errors}, status=400)
781
+ except Exception as exc:
782
+ logger.error("API create network: %s", exc)
783
+ return JsonResponse({'success': False, 'error': 'An internal error occurred. Check server logs.'}, status=500)
784
+
785
+ SNMPDeploymentState.mark_config_changed()
786
+ logger.info("API: network '%s' (id=%s) created by %s.", name, net.id, request.user.username)
787
+ return JsonResponse({'success': True, 'id': net.id, 'message': 'Network created successfully.'}, status=201)
788
+
789
+
790
+ @csrf_exempt
791
+ def network_detail(request, network_id):
792
+ """Read, update, or delete a single network."""
793
+ if request.method == 'GET':
794
+ return _get_network(request, network_id)
795
+ if request.method == 'PUT':
796
+ return _update_network(request, network_id)
797
+ if request.method == 'DELETE':
798
+ return _delete_network(request, network_id)
799
+ return JsonResponse({'error': 'Method not allowed'}, status=405)
800
+
801
+
802
+ @api_require_auth
803
+ def _get_network(request, network_id):
804
+ try:
805
+ net = Network.objects.select_related('connection', 'agent_connection').get(pk=network_id)
806
+ except Network.DoesNotExist:
807
+ return JsonResponse({'success': False, 'error': 'Network not found.'}, status=404)
808
+ from django.db.models import Count
809
+ device_count = net.devices.count()
810
+ return JsonResponse({'success': True, 'network': _network_data(net, device_count)})
811
+
812
+
813
+ @api_require_admin
814
+ def _update_network(request, network_id):
815
+ try:
816
+ net = Network.objects.select_related('connection', 'agent_connection').get(pk=network_id)
817
+ except Network.DoesNotExist:
818
+ return JsonResponse({'success': False, 'error': 'Network not found.'}, status=404)
819
+
820
+ data = parse_request_body(request)
821
+ _apply_network_fields(data, net)
822
+
823
+ network_range = net.network_range
824
+ ok, err = _validate_network_cidr(network_range)
825
+ if not ok:
826
+ return JsonResponse({'success': False, 'error': err}, status=400)
827
+
828
+ if not net.namespace_from_device_template:
829
+ ns_valid, ns_error = validate_namespace(net.namespace)
830
+ if not ns_valid:
831
+ return JsonResponse({'success': False, 'error': ns_error}, status=400)
832
+
833
+ try:
834
+ net.save()
835
+ except ValidationError as exc:
836
+ errors = exc.message_dict if hasattr(exc, 'message_dict') else {'error': exc.messages}
837
+ return JsonResponse({'success': False, 'error': errors}, status=400)
838
+ except Exception as exc:
839
+ logger.error("API update network %s: %s", network_id, exc)
840
+ return JsonResponse({'success': False, 'error': 'An internal error occurred. Check server logs.'}, status=500)
841
+
842
+ SNMPDeploymentState.mark_config_changed()
843
+ logger.info("API: network %s updated by %s.", network_id, request.user.username)
844
+ return JsonResponse({'success': True, 'id': net.id, 'message': 'Network updated successfully.'})
845
+
846
+
847
+ @api_require_admin
848
+ def _delete_network(request, network_id):
849
+ try:
850
+ net = Network.objects.get(pk=network_id)
851
+ except Network.DoesNotExist:
852
+ return JsonResponse({'success': False, 'error': 'Network not found.'}, status=404)
853
+
854
+ name = net.name
855
+ pipeline_name = f"snmp-{_sanitize_pipeline_name_component(name)}-polling"
856
+ trap_pipeline_name = f"snmp-{_sanitize_pipeline_name_component(name)}-traps"
857
+ pipeline_deleted = trap_deleted = False
858
+ pipeline_error = None
859
+
860
+ if net.connection:
861
+ try:
862
+ es = get_elastic_connection(net.connection.id)
863
+ for pid, flag_attr in ((pipeline_name, 'pipeline_deleted'), (trap_pipeline_name, 'trap_deleted')):
864
+ try:
865
+ existing = es.logstash.get_pipeline(id=pid)
866
+ if pid in existing:
867
+ es.logstash.delete_pipeline(id=pid)
868
+ if flag_attr == 'pipeline_deleted':
869
+ pipeline_deleted = True
870
+ else:
871
+ trap_deleted = True
872
+ except Exception:
873
+ pass
874
+ except Exception as exc:
875
+ pipeline_error = str(exc)
876
+
877
+ net.delete()
878
+ SNMPDeploymentState.mark_config_changed()
879
+ logger.warning("API: network '%s' (id=%s) deleted by %s.", name, network_id, request.user.username)
880
+
881
+ deleted_items = []
882
+ if pipeline_deleted:
883
+ deleted_items.append(f'pipeline "{pipeline_name}"')
884
+ if trap_deleted:
885
+ deleted_items.append(f'trap pipeline "{trap_pipeline_name}"')
886
+
887
+ if deleted_items:
888
+ msg = f"Network and {', '.join(deleted_items)} deleted successfully."
889
+ elif pipeline_error:
890
+ msg = f"Network deleted. Pipeline cleanup failed: {pipeline_error}"
891
+ else:
892
+ msg = f"Network '{name}' deleted."
893
+
894
+ return JsonResponse({'success': True, 'message': msg})
895
+
896
+
897
+ # ===========================================================================
898
+ # PROFILES
899
+ # ===========================================================================
900
+
901
+ def _profile_list_data(p):
902
+ return {
903
+ 'id': p.id,
904
+ 'name': p.name,
905
+ 'vendor': p.vendor or '',
906
+ 'product': p.product or '',
907
+ 'description': p.description or '',
908
+ 'is_official': p.name.endswith('.json'),
909
+ 'created_at': p.created_at.isoformat(),
910
+ }
911
+
912
+
913
+ def _profile_detail_data(p):
914
+ """Return one profile, reading official profiles' OIDs from their bundled JSON file.
915
+
916
+ Official rows only hold an ``is_official_placeholder`` marker in the database.
917
+ """
918
+ profile_data = p.profile_data or {}
919
+ normalizers = p.normalizers or []
920
+ if profile_data.get('is_official_placeholder'):
921
+ from SNMP.snmp_test import load_profile_data
922
+ official = load_profile_data(p)
923
+ profile_data = {key: official.get(key) or {} for key in ('get', 'walk', 'table')}
924
+ normalizers = official.get('normalizers') or normalizers
925
+ return {
926
+ 'id': p.id,
927
+ 'name': p.name,
928
+ 'vendor': p.vendor or '',
929
+ 'product': p.product or '',
930
+ 'description': p.description or '',
931
+ 'is_official': p.name.endswith('.json'),
932
+ 'profile_data': profile_data,
933
+ 'normalizers': normalizers,
934
+ 'created_at': p.created_at.isoformat(),
935
+ 'updated_at': p.updated_at.isoformat(),
936
+ }
937
+
938
+
939
+ @csrf_exempt
940
+ def profile_list(request):
941
+ """List all profiles or create a new one."""
942
+ if request.method == 'GET':
943
+ return _list_profiles(request)
944
+ if request.method == 'POST':
945
+ return _create_profile(request)
946
+ return JsonResponse({'error': 'Method not allowed'}, status=405)
947
+
948
+
949
+ @api_require_auth
950
+ def _list_profiles(request):
951
+ qs = Profile.objects.all().order_by('name')
952
+ search = request.GET.get('search', '').strip()
953
+ if search:
954
+ qs = qs.filter(Q(name__icontains=search) | Q(vendor__icontains=search))
955
+ official_filter = request.GET.get('official', '').strip().lower()
956
+ # M15 fix: previously converted the entire queryset to a Python list before
957
+ # filtering, loading every row into memory. Use ORM __endswith filter instead.
958
+ if official_filter == 'true':
959
+ qs = qs.filter(name__endswith='.json')
960
+ elif official_filter == 'false':
961
+ qs = qs.exclude(name__endswith='.json')
962
+
963
+ items = [_profile_list_data(p) for p in qs]
964
+ return JsonResponse({'profiles': items, 'total': len(items)})
965
+
966
+
967
+ _OFFICIAL_MARKER_ERROR = 'profile_data cannot contain is_official_placeholder; it is reserved for official profiles.'
968
+
969
+
970
+ def _claims_official(profile_data):
971
+ """Return True when user-supplied ``profile_data`` carries the official-row marker.
972
+
973
+ Examples:
974
+ >>> _claims_official({'is_official_placeholder': True})
975
+ True
976
+ >>> _claims_official({'get': {}})
977
+ False
978
+ """
979
+ return isinstance(profile_data, dict) and 'is_official_placeholder' in profile_data
980
+
981
+
982
+ @api_require_admin
983
+ def _create_profile(request):
984
+ data = parse_request_body(request)
985
+ name = (data.get('name') or '').strip()
986
+ if not name:
987
+ return JsonResponse({'success': False, 'error': 'name is required.'}, status=400)
988
+ vendor = (data.get('vendor') or '').strip()
989
+ if not vendor:
990
+ return JsonResponse({'success': False, 'error': 'vendor is required.'}, status=400)
991
+
992
+ if Profile.objects.filter(name=name).exists():
993
+ # H7/M7 fix: duplicate profile should return 409 Conflict, not 400.
994
+ return JsonResponse({'success': False, 'error': 'A profile with this name already exists.'}, status=409)
995
+ if _claims_official(data.get('profile_data')):
996
+ return JsonResponse({'success': False, 'error': _OFFICIAL_MARKER_ERROR}, status=400)
997
+
998
+ profile = Profile(
999
+ name=name,
1000
+ description=data.get('description', '') or '',
1001
+ vendor=vendor,
1002
+ product=data.get('product', '') or '',
1003
+ profile_data=data.get('profile_data', {}) or {},
1004
+ normalizers=data.get('normalizers', []) or [],
1005
+ )
1006
+ try:
1007
+ profile.save()
1008
+ except ValidationError as exc:
1009
+ errors = exc.message_dict if hasattr(exc, 'message_dict') else {'error': exc.messages}
1010
+ return JsonResponse({'success': False, 'error': errors}, status=400)
1011
+ except IntegrityError:
1012
+ return JsonResponse({'success': False, 'error': 'A profile with this name already exists.'}, status=409)
1013
+ except Exception as exc:
1014
+ logger.error("API create profile: %s", exc)
1015
+ return JsonResponse({'success': False, 'error': 'An internal error occurred. Check server logs.'}, status=500)
1016
+
1017
+ SNMPDeploymentState.mark_config_changed()
1018
+ logger.info("API: profile '%s' (id=%s) created by %s.", name, profile.id, request.user.username)
1019
+ return JsonResponse({'success': True, 'id': profile.id, 'message': 'Profile created successfully.'}, status=201)
1020
+
1021
+
1022
+ @csrf_exempt
1023
+ def profile_detail(request, profile_id):
1024
+ """Read, update, or delete a single profile."""
1025
+ if request.method == 'GET':
1026
+ return _get_profile(request, profile_id)
1027
+ if request.method == 'PUT':
1028
+ return _update_profile(request, profile_id)
1029
+ if request.method == 'DELETE':
1030
+ return _delete_profile(request, profile_id)
1031
+ return JsonResponse({'error': 'Method not allowed'}, status=405)
1032
+
1033
+
1034
+ @api_require_auth
1035
+ def _get_profile(request, profile_id):
1036
+ try:
1037
+ p = Profile.objects.get(pk=profile_id)
1038
+ except Profile.DoesNotExist:
1039
+ return JsonResponse({'success': False, 'error': 'Profile not found.'}, status=404)
1040
+ return JsonResponse({'success': True, 'profile': _profile_detail_data(p)})
1041
+
1042
+
1043
+ @api_require_admin
1044
+ def _update_profile(request, profile_id):
1045
+ try:
1046
+ p = Profile.objects.get(pk=profile_id)
1047
+ except Profile.DoesNotExist:
1048
+ return JsonResponse({'success': False, 'error': 'Profile not found.'}, status=404)
1049
+
1050
+ if p.name.endswith('.json'):
1051
+ return protected_response('Official profiles cannot be modified. Create a custom profile with a new name instead.')
1052
+
1053
+ data = parse_request_body(request)
1054
+
1055
+ new_name = (data.get('name') or p.name).strip()
1056
+ if new_name != p.name and Profile.objects.filter(name=new_name).exists():
1057
+ return JsonResponse({'success': False, 'error': 'A profile with this name already exists.'}, status=400)
1058
+ p.name = new_name
1059
+ if 'description' in data:
1060
+ p.description = data['description'] or ''
1061
+ if 'vendor' in data:
1062
+ p.vendor = data['vendor'] or ''
1063
+ if 'product' in data:
1064
+ p.product = data['product'] or ''
1065
+ if 'profile_data' in data:
1066
+ if _claims_official(data['profile_data']):
1067
+ return JsonResponse({'success': False, 'error': _OFFICIAL_MARKER_ERROR}, status=400)
1068
+ p.profile_data = data['profile_data'] or {}
1069
+ if 'normalizers' in data:
1070
+ p.normalizers = data['normalizers'] or []
1071
+
1072
+ try:
1073
+ p.save()
1074
+ except ValidationError as exc:
1075
+ errors = exc.message_dict if hasattr(exc, 'message_dict') else {'error': exc.messages}
1076
+ return JsonResponse({'success': False, 'error': errors}, status=400)
1077
+ except Exception as exc:
1078
+ logger.error("API update profile %s: %s", profile_id, exc)
1079
+ return JsonResponse({'success': False, 'error': 'An internal error occurred. Check server logs.'}, status=500)
1080
+
1081
+ SNMPDeploymentState.mark_config_changed()
1082
+ logger.info("API: profile %s updated by %s.", profile_id, request.user.username)
1083
+ return JsonResponse({'success': True, 'id': p.id, 'message': 'Profile updated successfully.'})
1084
+
1085
+
1086
+ @api_require_admin
1087
+ def _delete_profile(request, profile_id):
1088
+ try:
1089
+ p = Profile.objects.get(pk=profile_id)
1090
+ except Profile.DoesNotExist:
1091
+ return JsonResponse({'success': False, 'error': 'Profile not found.'}, status=404)
1092
+
1093
+ # Bug 3 fix: protect ALL official profiles (name ends in .json), not just
1094
+ # the two that were hard-coded before.
1095
+ if p.name.endswith('.json'):
1096
+ return protected_response('Official profiles cannot be deleted.')
1097
+
1098
+ name = p.name
1099
+ p.delete()
1100
+ SNMPDeploymentState.mark_config_changed()
1101
+ logger.warning("API: profile '%s' (id=%s) deleted by %s.", name, profile_id, request.user.username)
1102
+ return JsonResponse({'success': True, 'message': f"Profile '{name}' deleted."})
1103
+
1104
+
1105
+ # ===========================================================================
1106
+ # DEVICE TEMPLATES
1107
+ # ===========================================================================
1108
+
1109
+ def _template_list_data(t):
1110
+ return {
1111
+ 'id': t.id,
1112
+ 'name': t.name,
1113
+ 'vendor': t.vendor or '',
1114
+ 'model': t.model or '',
1115
+ 'product': t.product or '',
1116
+ 'type': t.type or '',
1117
+ 'official': t.official,
1118
+ 'description': t.description or '',
1119
+ 'created_at': t.created_at.isoformat(),
1120
+ }
1121
+
1122
+
1123
+ def _template_detail_data(t):
1124
+ return {
1125
+ 'id': t.id,
1126
+ 'name': t.name,
1127
+ 'description': t.description or '',
1128
+ 'vendor': t.vendor or '',
1129
+ 'model': t.model or '',
1130
+ 'product': t.product or '',
1131
+ 'type': t.type or '',
1132
+ 'official': t.official,
1133
+ 'matching_rules': t.matching_rules or [],
1134
+ 'profiles': [
1135
+ {'id': p.id, 'name': p.name}
1136
+ for p in t.profiles.all()
1137
+ ],
1138
+ 'created_at': t.created_at.isoformat(),
1139
+ 'updated_at': t.updated_at.isoformat(),
1140
+ }
1141
+
1142
+
1143
+ def _set_template_profiles(template, profile_ids):
1144
+ """Set the M2M profiles on a template from a list of int ids or name strings.
1145
+
1146
+ M17 fix: previously issued one SELECT per profile_id (N+1 queries).
1147
+ Now fetches all matching profiles in two bulk queries (by id and by name).
1148
+
1149
+ Returns a list of ids/names that were not found (skipped).
1150
+ """
1151
+ int_ids = []
1152
+ str_names = []
1153
+ for pid in profile_ids:
1154
+ pid_str = str(pid).strip()
1155
+ if pid_str.isdigit():
1156
+ int_ids.append(int(pid_str))
1157
+ else:
1158
+ str_names.append(pid_str)
1159
+
1160
+ profiles_by_id = {}
1161
+ if int_ids:
1162
+ for p in Profile.objects.filter(id__in=int_ids):
1163
+ profiles_by_id[p.id] = p
1164
+
1165
+ profiles_by_name = {}
1166
+ if str_names:
1167
+ for p in Profile.objects.filter(name__in=str_names):
1168
+ profiles_by_name[p.name] = p
1169
+
1170
+ profiles_to_add = []
1171
+ skipped = []
1172
+ for pid in profile_ids:
1173
+ pid_str = str(pid).strip()
1174
+ if pid_str.isdigit():
1175
+ p = profiles_by_id.get(int(pid_str))
1176
+ else:
1177
+ p = profiles_by_name.get(pid_str)
1178
+ if p:
1179
+ profiles_to_add.append(p)
1180
+ else:
1181
+ skipped.append(pid)
1182
+
1183
+ template.profiles.clear()
1184
+ if profiles_to_add:
1185
+ template.profiles.add(*profiles_to_add)
1186
+ return skipped
1187
+
1188
+
1189
+ @csrf_exempt
1190
+ def template_list(request):
1191
+ """List all device templates or create a new one."""
1192
+ if request.method == 'GET':
1193
+ return _list_templates(request)
1194
+ if request.method == 'POST':
1195
+ return _create_template(request)
1196
+ return JsonResponse({'error': 'Method not allowed'}, status=405)
1197
+
1198
+
1199
+ @api_require_auth
1200
+ def _list_templates(request):
1201
+ qs = DeviceTemplate.objects.all().order_by('name')
1202
+ search = request.GET.get('search', '').strip()
1203
+ if search:
1204
+ qs = qs.filter(Q(name__icontains=search) | Q(vendor__icontains=search))
1205
+ official_filter = request.GET.get('official', '').strip().lower()
1206
+ if official_filter == 'true':
1207
+ qs = qs.filter(official=True)
1208
+ elif official_filter == 'false':
1209
+ qs = qs.filter(official=False)
1210
+
1211
+ items = [_template_list_data(t) for t in qs]
1212
+ return JsonResponse({'templates': items, 'total': len(items)})
1213
+
1214
+
1215
+ @api_require_admin
1216
+ def _create_template(request):
1217
+ data = parse_request_body(request)
1218
+ name = (data.get('name') or '').strip()
1219
+ if not name:
1220
+ return JsonResponse({'success': False, 'error': 'name is required.'}, status=400)
1221
+ vendor = (data.get('vendor') or '').strip()
1222
+ if not vendor:
1223
+ return JsonResponse({'success': False, 'error': 'vendor is required.'}, status=400)
1224
+
1225
+ matching_rules = data.get('matching_rules', []) or []
1226
+ if not isinstance(matching_rules, list):
1227
+ return JsonResponse({'success': False, 'error': 'matching_rules must be a list.'}, status=400)
1228
+
1229
+ try:
1230
+ template = DeviceTemplate(
1231
+ name=name,
1232
+ description=data.get('description', '') or '',
1233
+ vendor=vendor,
1234
+ model=data.get('model', '') or '',
1235
+ product=data.get('product', '') or '',
1236
+ type=data.get('type', '') or '',
1237
+ matching_rules=matching_rules,
1238
+ official=False,
1239
+ )
1240
+ template.save()
1241
+ except ValidationError as exc:
1242
+ errors = exc.message_dict if hasattr(exc, 'message_dict') else {'error': exc.messages}
1243
+ return JsonResponse({'success': False, 'error': errors}, status=400)
1244
+ except Exception as exc:
1245
+ logger.error("API create template: %s", exc)
1246
+ return JsonResponse({'success': False, 'error': 'An internal error occurred. Check server logs.'}, status=500)
1247
+
1248
+ skipped = _set_template_profiles(template, data.get('profiles', []) or [])
1249
+ SNMPDeploymentState.mark_config_changed()
1250
+ logger.info("API: template '%s' (id=%s) created by %s.", name, template.id, request.user.username)
1251
+
1252
+ resp = {'success': True, 'id': template.id, 'message': 'Device template created successfully.'}
1253
+ if skipped:
1254
+ resp['skipped_profiles'] = skipped
1255
+ return JsonResponse(resp, status=201)
1256
+
1257
+
1258
+ @csrf_exempt
1259
+ def template_detail(request, template_id):
1260
+ """Read, update, or delete a single device template."""
1261
+ if request.method == 'GET':
1262
+ return _get_template(request, template_id)
1263
+ if request.method == 'PUT':
1264
+ return _update_template(request, template_id)
1265
+ if request.method == 'DELETE':
1266
+ return _delete_template(request, template_id)
1267
+ return JsonResponse({'error': 'Method not allowed'}, status=405)
1268
+
1269
+
1270
+ @api_require_auth
1271
+ def _get_template(request, template_id):
1272
+ try:
1273
+ t = DeviceTemplate.objects.prefetch_related('profiles').get(pk=template_id)
1274
+ except DeviceTemplate.DoesNotExist:
1275
+ return JsonResponse({'success': False, 'error': 'Device template not found.'}, status=404)
1276
+ return JsonResponse({'success': True, 'template': _template_detail_data(t)})
1277
+
1278
+
1279
+ @api_require_admin
1280
+ def _update_template(request, template_id):
1281
+ try:
1282
+ t = DeviceTemplate.objects.prefetch_related('profiles').get(pk=template_id)
1283
+ except DeviceTemplate.DoesNotExist:
1284
+ return JsonResponse({'success': False, 'error': 'Device template not found.'}, status=404)
1285
+
1286
+ if t.official:
1287
+ return protected_response('Official templates cannot be modified.')
1288
+
1289
+ data = parse_request_body(request)
1290
+ if 'name' in data and data['name']:
1291
+ t.name = data['name'].strip()
1292
+ if 'description' in data:
1293
+ t.description = data['description'] or ''
1294
+ if 'vendor' in data and data['vendor']:
1295
+ t.vendor = data['vendor'].strip()
1296
+ if 'model' in data:
1297
+ t.model = data['model'] or ''
1298
+ if 'product' in data:
1299
+ t.product = data['product'] or ''
1300
+ if 'type' in data:
1301
+ t.type = data['type'] or ''
1302
+ if 'matching_rules' in data:
1303
+ rules = data['matching_rules'] or []
1304
+ if not isinstance(rules, list):
1305
+ return JsonResponse({'success': False, 'error': 'matching_rules must be a list.'}, status=400)
1306
+ t.matching_rules = rules
1307
+
1308
+ try:
1309
+ t.save()
1310
+ except ValidationError as exc:
1311
+ errors = exc.message_dict if hasattr(exc, 'message_dict') else {'error': exc.messages}
1312
+ return JsonResponse({'success': False, 'error': errors}, status=400)
1313
+ except Exception as exc:
1314
+ logger.error("API update template %s: %s", template_id, exc)
1315
+ return JsonResponse({'success': False, 'error': 'An internal error occurred. Check server logs.'}, status=500)
1316
+
1317
+ skipped = []
1318
+ if 'profiles' in data:
1319
+ skipped = _set_template_profiles(t, data['profiles'] or [])
1320
+
1321
+ SNMPDeploymentState.mark_config_changed()
1322
+ logger.info("API: template %s updated by %s.", template_id, request.user.username)
1323
+ resp = {'success': True, 'id': t.id, 'message': 'Device template updated successfully.'}
1324
+ if skipped:
1325
+ resp['skipped_profiles'] = skipped
1326
+ return JsonResponse(resp)
1327
+
1328
+
1329
+ @api_require_admin
1330
+ def _delete_template(request, template_id):
1331
+ try:
1332
+ t = DeviceTemplate.objects.get(pk=template_id)
1333
+ except DeviceTemplate.DoesNotExist:
1334
+ return JsonResponse({'success': False, 'error': 'Device template not found.'}, status=404)
1335
+
1336
+ if t.official:
1337
+ return protected_response('Official templates cannot be deleted.')
1338
+
1339
+ name = t.name
1340
+ t.delete() # DeviceTemplate.delete() reassigns devices to the default template
1341
+ SNMPDeploymentState.mark_config_changed()
1342
+ logger.warning("API: template '%s' (id=%s) deleted by %s.", name, template_id, request.user.username)
1343
+ return JsonResponse({'success': True, 'message': f"Device template '{name}' deleted."})
1344
+
1345
+
1346
+ # ===========================================================================
1347
+ # DEPLOY
1348
+ # ===========================================================================
1349
+
1350
+ @csrf_exempt
1351
+ @api_require_auth
1352
+ def deploy_status(request):
1353
+ """Check whether there are undeployed SNMP configuration changes.
1354
+
1355
+ GET /api/snmp/deploy/status/
1356
+ Any authenticated user.
1357
+ """
1358
+ if request.method != 'GET':
1359
+ return JsonResponse({'error': 'Method not allowed'}, status=405)
1360
+ try:
1361
+ has_changes = SNMPDeploymentState.has_undeployed_changes()
1362
+ return JsonResponse({'success': True, 'has_changes': has_changes})
1363
+ except Exception as exc:
1364
+ logger.error("API deploy status: %s", exc)
1365
+ # H4 fix: returning success:True on exception was misleading.
1366
+ # Return 500 so callers can distinguish an error from a real status.
1367
+ return JsonResponse({'success': False, 'error': 'An internal error occurred. Check server logs.'}, status=500)
1368
+
1369
+
1370
+ @csrf_exempt
1371
+ @api_require_admin
1372
+ def deploy_diff(request):
1373
+ """Compute and return the deployment diff (desired vs actual pipelines).
1374
+
1375
+ POST /api/snmp/deploy/diff/
1376
+ Admin only. Caches the full plan for 60 seconds so a subsequent
1377
+ POST /api/snmp/deploy/apply/ can reuse it without recomputing.
1378
+
1379
+ Body (all optional):
1380
+ detail: ``full`` (default) returns each entry's raw ``current`` and
1381
+ ``new`` config. ``summary`` returns ``counts`` and one row per
1382
+ change without config. ``changes`` is ``summary`` plus a unified
1383
+ ``diff`` per entry. Secret values in config (community strings,
1384
+ passwords, API keys) are always returned as ``[redacted]``.
1385
+ pipelines: Pipeline names to restrict ``changes``/``full`` entries to.
1386
+ ``counts`` always cover the whole plan.
1387
+
1388
+ Example:
1389
+ curl -X POST -H "Authorization: ApiKey $KEY" -H "Content-Type: application/json" \\
1390
+ -d '{"detail": "changes", "pipelines": ["snmp-lab-discovery"]}' \\
1391
+ https://logstashui.example.com/api/snmp/deploy/diff/
1392
+ """
1393
+ if request.method != 'POST':
1394
+ return JsonResponse({'error': 'Method not allowed'}, status=405)
1395
+ data = parse_request_body(request)
1396
+ detail = data.get('detail') or 'full'
1397
+ if detail not in _DIFF_DETAILS:
1398
+ return JsonResponse({'success': False, 'error': f"detail must be one of: {', '.join(_DIFF_DETAILS)}."}, status=400)
1399
+ names = data.get('pipelines')
1400
+ if names is not None and (not isinstance(names, list) or not all(isinstance(n, str) for n in names)):
1401
+ return JsonResponse({'success': False, 'error': 'pipelines must be a list of pipeline names.'}, status=400)
1402
+ try:
1403
+ from SNMP.snmp_crud import GetDeployDiff
1404
+ response = GetDeployDiff(request)
1405
+ if response.status_code != 200:
1406
+ return response
1407
+ return JsonResponse(_shape_deploy_diff(json.loads(response.content), detail, names))
1408
+ except Exception as exc:
1409
+ logger.error("API deploy diff: %s", exc)
1410
+ return JsonResponse({'success': False, 'error': 'An internal error occurred. Check server logs.'}, status=500)
1411
+
1412
+
1413
+ _DIFF_DETAILS = ('full', 'summary', 'changes')
1414
+
1415
+ #: Diff entry keys kept in ``summary`` and ``changes`` rows.
1416
+ _DIFF_ROW_KEYS = ('pipeline_name', 'action', 'pipeline_type', 'network_name', 'template_name',
1417
+ 'deployment_mode', 'destination_type', 'destination_name', 'connection_id',
1418
+ 'agent_policy_id', 'manual_keystore_keys', 'note')
1419
+
1420
+ _SECRET_KEYS = r'(?:api_key|cloud_auth|community|auth_pass|priv_pass|\w*password)'
1421
+
1422
+ #: One LSCL string token, as the Logstash grammar reads it (may span lines).
1423
+ _LSCL_STRING = r'''"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*\''''
1424
+
1425
+ #: A secret setting (bare or quoted key) and its value: one string or a list of strings.
1426
+ _SECRET_SETTING_RE = re.compile(
1427
+ rf'''((?:\b{_SECRET_KEYS}\b|(["']){_SECRET_KEYS}\2)\s*=>\s*)'''
1428
+ rf'''({_LSCL_STRING}|\[\s*(?:(?:{_LSCL_STRING})\s*,?\s*)*\])''',
1429
+ re.DOTALL,
1430
+ )
1431
+
1432
+ _KEYSTORE_REF_RE = re.compile(r'''(["'])\$\{[^}]*\}\1''')
1433
+
1434
+
1435
+ def _mask_string(match):
1436
+ token = match.group(0)
1437
+ return token if _KEYSTORE_REF_RE.fullmatch(token) else f'{token[0]}[redacted]{token[0]}'
1438
+
1439
+
1440
+ def _mask_secrets(lscl):
1441
+ """Replace secret values in generated LSCL with ``[redacted]``.
1442
+
1443
+ Every string in a secret setting's value is masked, including list items
1444
+ (the snmptrap ``community`` list), quoted keys, and values that span
1445
+ lines. A value that is exactly a ``${VAR}`` keystore reference is kept.
1446
+
1447
+ Examples:
1448
+ >>> _mask_secrets('community => "public" api_key => "${ES_KEY}"')
1449
+ 'community => "[redacted]" api_key => "${ES_KEY}"'
1450
+ >>> _mask_secrets('"community" => ["a", \\'b\\']')
1451
+ '"community" => ["[redacted]", \\'[redacted]\\']'
1452
+ """
1453
+ return _SECRET_SETTING_RE.sub(
1454
+ lambda m: m.group(1) + re.sub(_LSCL_STRING, _mask_string, m.group(3), flags=re.DOTALL),
1455
+ lscl or '',
1456
+ )
1457
+
1458
+
1459
+ def _diff_counts(entries):
1460
+ """Count plan entries the way ``snmp_deploy_apply`` reports them.
1461
+
1462
+ Keystore-drift entries are counted as ``keystore_updates`` and error
1463
+ entries as ``errors``; neither adds to the pipeline counts.
1464
+
1465
+ Examples:
1466
+ >>> _diff_counts([{'action': 'update', 'pipeline_type': 'polling'},
1467
+ ... {'action': 'update', 'pipeline_type': 'keystore'}])
1468
+ {'create': 0, 'update': 1, 'delete': 0, 'keystore_updates': 1, 'errors': 0}
1469
+ """
1470
+ counts = {'create': 0, 'update': 0, 'delete': 0, 'keystore_updates': 0, 'errors': 0}
1471
+ for entry in entries:
1472
+ action = entry.get('action')
1473
+ if action == 'error':
1474
+ counts['errors'] += 1
1475
+ elif entry.get('pipeline_type') == 'keystore':
1476
+ counts['keystore_updates'] += 1
1477
+ elif action in ('create', 'update', 'delete'):
1478
+ counts[action] += 1
1479
+ return counts
1480
+
1481
+
1482
+ def _shape_deploy_diff(plan, detail, names):
1483
+ """Reduce a full ``GetDeployDiff`` payload to the requested detail level.
1484
+
1485
+ Args:
1486
+ plan: Decoded full diff payload.
1487
+ detail: ``summary``, ``changes``, or ``full``.
1488
+ names: Optional pipeline names to keep in ``networks``.
1489
+
1490
+ Returns:
1491
+ dict: The payload with ``counts`` added, ``networks`` trimmed, and
1492
+ secret values in ``current``/``new`` config masked.
1493
+ """
1494
+ import difflib
1495
+
1496
+ entries = [{**e, 'current': _mask_secrets(e.get('current')), 'new': _mask_secrets(e.get('new'))}
1497
+ for e in plan.get('networks') or []]
1498
+ shaped = {**plan, 'counts': _diff_counts(entries)}
1499
+ if names is not None:
1500
+ wanted = set(names)
1501
+ entries = [e for e in entries if e.get('pipeline_name') in wanted]
1502
+ if detail == 'full':
1503
+ shaped['networks'] = entries
1504
+ return shaped
1505
+
1506
+ rows = []
1507
+ for entry in entries:
1508
+ row = {key: entry[key] for key in _DIFF_ROW_KEYS if entry.get(key) not in (None, '', [])}
1509
+ if detail == 'changes':
1510
+ row['diff'] = ''.join(difflib.unified_diff(
1511
+ entry['current'].splitlines(keepends=True),
1512
+ entry['new'].splitlines(keepends=True),
1513
+ fromfile='current', tofile='new', n=2,
1514
+ ))
1515
+ rows.append(row)
1516
+ shaped['networks'] = rows
1517
+ return shaped
1518
+
1519
+
1520
+ @csrf_exempt
1521
+ @api_require_admin
1522
+ def deploy_apply(request):
1523
+ """Apply the SNMP configuration — push pipelines to ES / agent records.
1524
+
1525
+ POST /api/snmp/deploy/apply/
1526
+ Admin only. Reuses the cached diff from a preceding call to
1527
+ POST /api/snmp/deploy/diff/ if available; otherwise performs a full
1528
+ reconciliation.
1529
+
1530
+ Returns counts of pipelines created / updated / deleted and any errors.
1531
+ """
1532
+ if request.method != 'POST':
1533
+ return JsonResponse({'error': 'Method not allowed'}, status=405)
1534
+ try:
1535
+ from SNMP.snmp_crud import DeployConfiguration
1536
+ return DeployConfiguration(request)
1537
+ except Exception as exc:
1538
+ logger.error("API deploy apply: %s", exc)
1539
+ return JsonResponse({'success': False, 'error': 'An internal error occurred. Check server logs.'}, status=500)