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.
- AI/__init__.py +0 -0
- AI/integration_factory.py +1392 -0
- AI/migrations/0001_initial.py +58 -0
- AI/migrations/0002_draftdefinition_normalizers.py +23 -0
- AI/migrations/0003_delete_aisettings_delete_draftdefinition.py +19 -0
- AI/migrations/__init__.py +0 -0
- AI/models.py +5 -0
- AI/static/js/integration_factory.js +1102 -0
- AI/system_prompts/dashboard_generator.md +367 -0
- AI/system_prompts/grok_patterns.txt +95 -0
- AI/system_prompts/ingest_pipeline_generator.md +331 -0
- AI/system_prompts/ingest_pipeline_processors.json +2851 -0
- AI/system_prompts/ingest_verifier.md +84 -0
- AI/system_prompts/integrations_list.json +2690 -0
- AI/system_prompts/log_classifier.md +134 -0
- AI/system_prompts/template_creator.md +123 -0
- AI/templates/integration_factory.html +200 -0
- AI/urls.py +16 -0
- AI/views.py +20 -0
- API/__init__.py +0 -0
- API/admin.py +7 -0
- API/api.http +784 -0
- API/apps.py +9 -0
- API/auth.py +101 -0
- API/connections_views.py +312 -0
- API/guides.py +88 -0
- API/mcp/__init__.py +5 -0
- API/mcp/dispatch.py +179 -0
- API/mcp/tools.py +890 -0
- API/mcp/views.py +215 -0
- API/migrations/__init__.py +0 -0
- API/models.py +7 -0
- API/pipelines_views.py +1224 -0
- API/policies_views.py +1015 -0
- API/security_views.py +488 -0
- API/simulation_detail.py +219 -0
- API/snmp_views.py +1539 -0
- API/urls.py +81 -0
- Common/__init__.py +0 -0
- Common/ai/agent_builder.py +690 -0
- Common/context_processors.py +49 -0
- Common/decorators.py +68 -0
- Common/elastic_utils.py +1154 -0
- Common/encryption.py +271 -0
- Common/error_handlers.py +65 -0
- Common/formatters.py +106 -0
- Common/logstash_config_parse.py +1469 -0
- Common/logstash_utils.py +34 -0
- Common/middleware.py +216 -0
- Common/product_ca.py +1124 -0
- Common/validators.py +66 -0
- Documentation/__init__.py +0 -0
- Documentation/admin.py +7 -0
- Documentation/apps.py +9 -0
- Documentation/content/CHANGELOG.md +890 -0
- Documentation/content/docs/getting_started.md +92 -0
- Documentation/content/docs/index.md +124 -0
- Documentation/content/docs/logstashagent/configuration/index.md +60 -0
- Documentation/content/docs/logstashagent/configuration/logstashagent.yml.md +141 -0
- Documentation/content/docs/logstashagent/general/build.md +217 -0
- Documentation/content/docs/logstashagent/general/index.md +38 -0
- Documentation/content/docs/logstashagent/general/roles.md +267 -0
- Documentation/content/docs/logstashagent/index.md +264 -0
- Documentation/content/docs/logstashui/SNMP/Quickstart.md +94 -0
- Documentation/content/docs/logstashui/SNMP/architecture.md +64 -0
- Documentation/content/docs/logstashui/SNMP/configuration.md +147 -0
- Documentation/content/docs/logstashui/SNMP/data_overview.md +59 -0
- Documentation/content/docs/logstashui/SNMP/deploying_changes.md +71 -0
- Documentation/content/docs/logstashui/SNMP/device_support.md +39 -0
- Documentation/content/docs/logstashui/SNMP/discovery.md +48 -0
- Documentation/content/docs/logstashui/SNMP/index.md +58 -0
- Documentation/content/docs/logstashui/SNMP/pipeline_generation.md +63 -0
- Documentation/content/docs/logstashui/SNMP/schema.md +595 -0
- Documentation/content/docs/logstashui/SNMP/testing.md +47 -0
- Documentation/content/docs/logstashui/SNMP/traps.md +45 -0
- Documentation/content/docs/logstashui/SNMP/tsds_implementation.md +82 -0
- Documentation/content/docs/logstashui/agent_guides/concepts.md +25 -0
- Documentation/content/docs/logstashui/agent_guides/deploy.md +30 -0
- Documentation/content/docs/logstashui/agent_guides/pipeline-review.md +24 -0
- Documentation/content/docs/logstashui/agent_guides/simulation.md +55 -0
- Documentation/content/docs/logstashui/agent_guides/snmp.md +57 -0
- Documentation/content/docs/logstashui/agent_guides/troubleshooting.md +21 -0
- Documentation/content/docs/logstashui/architecture.md +11 -0
- Documentation/content/docs/logstashui/compatibility.md +58 -0
- Documentation/content/docs/logstashui/configuration/environment.md +193 -0
- Documentation/content/docs/logstashui/configuration/host_mode.md +94 -0
- Documentation/content/docs/logstashui/configuration/index.md +72 -0
- Documentation/content/docs/logstashui/configuration/logstash_proxy.md +138 -0
- Documentation/content/docs/logstashui/configuration/logstashui.yml.md +16 -0
- Documentation/content/docs/logstashui/configuration/simulation.md +84 -0
- Documentation/content/docs/logstashui/database/examples/README.md +15 -0
- Documentation/content/docs/logstashui/database/examples/create-mariadb.sql +13 -0
- Documentation/content/docs/logstashui/database/examples/create-mysql.sql +12 -0
- Documentation/content/docs/logstashui/database/examples/create-postgresql.sql +13 -0
- Documentation/content/docs/logstashui/database/examples/schema-mysql.sql +502 -0
- Documentation/content/docs/logstashui/database/examples/schema-postgresql.sql +1709 -0
- Documentation/content/docs/logstashui/database/index.md +79 -0
- Documentation/content/docs/logstashui/database/migration.md +75 -0
- Documentation/content/docs/logstashui/general/build.md +154 -0
- Documentation/content/docs/logstashui/general/deploy.md +122 -0
- Documentation/content/docs/logstashui/general/deployment-recs.md +32 -0
- Documentation/content/docs/logstashui/general/index.md +62 -0
- Documentation/content/docs/logstashui/general/offline.md +68 -0
- Documentation/content/docs/logstashui/general/updating.md +50 -0
- Documentation/content/docs/logstashui/index.md +90 -0
- Documentation/content/docs/logstashui/kubernetes/cnpg.md +98 -0
- Documentation/content/docs/logstashui/kubernetes/envoy-gateway.md +112 -0
- Documentation/content/docs/logstashui/kubernetes/examples/README.md +46 -0
- Documentation/content/docs/logstashui/kubernetes/examples/embedded-agent.yaml +122 -0
- Documentation/content/docs/logstashui/kubernetes/examples/mysql/configmap.yaml +41 -0
- Documentation/content/docs/logstashui/kubernetes/examples/mysql/ingress.yaml +31 -0
- Documentation/content/docs/logstashui/kubernetes/examples/mysql/namespace.yaml +8 -0
- Documentation/content/docs/logstashui/kubernetes/examples/mysql/secret.yaml +19 -0
- Documentation/content/docs/logstashui/kubernetes/examples/mysql/statefulset.yaml +106 -0
- Documentation/content/docs/logstashui/kubernetes/examples/postgresql/cnpg.yaml +25 -0
- Documentation/content/docs/logstashui/kubernetes/examples/postgresql/configmap.yaml +42 -0
- Documentation/content/docs/logstashui/kubernetes/examples/postgresql/ingress.yaml +31 -0
- Documentation/content/docs/logstashui/kubernetes/examples/postgresql/namespace.yaml +8 -0
- Documentation/content/docs/logstashui/kubernetes/examples/postgresql/secret.yaml +19 -0
- Documentation/content/docs/logstashui/kubernetes/examples/postgresql/statefulset.yaml +106 -0
- Documentation/content/docs/logstashui/kubernetes/examples/sqlite/configmap.yaml +35 -0
- Documentation/content/docs/logstashui/kubernetes/examples/sqlite/ingress.yaml +31 -0
- Documentation/content/docs/logstashui/kubernetes/examples/sqlite/namespace.yaml +8 -0
- Documentation/content/docs/logstashui/kubernetes/examples/sqlite/secret.yaml +18 -0
- Documentation/content/docs/logstashui/kubernetes/examples/sqlite/statefulset.yaml +106 -0
- Documentation/content/docs/logstashui/kubernetes/index.md +121 -0
- Documentation/content/docs/logstashui/mcp.md +224 -0
- Documentation/content/docs/logstashui/mcp_scenarios.md +234 -0
- Documentation/content/docs/logstashui/rest_api.md +2783 -0
- Documentation/content/docs/logstashui/utilities/dissect_debugger.md +89 -0
- Documentation/content/docs/logstashui/utilities/grok_debugger.md +114 -0
- Documentation/content/docs/logstashui/utilities/index.md +40 -0
- Documentation/content/images/LogstashIcon.png +0 -0
- Documentation/content/images/architecture.png +0 -0
- Documentation/content/images/connection_manager.png +0 -0
- Documentation/content/images/control_plane.png +0 -0
- Documentation/content/images/graph.gif +0 -0
- Documentation/content/images/login.png +0 -0
- Documentation/content/images/monitoring.png +0 -0
- Documentation/content/images/new_connection.gif +0 -0
- Documentation/content/images/simulate.gif +0 -0
- Documentation/content/images/simulate.png +0 -0
- Documentation/content/images/snmp.gif +0 -0
- Documentation/content/images/snmp.png +0 -0
- Documentation/content/images/snmp_architecture.png +0 -0
- Documentation/migrations/__init__.py +0 -0
- Documentation/models.py +9 -0
- Documentation/static/css/markdown.css +250 -0
- Documentation/templates/documentation.html +225 -0
- Documentation/templates/nav_item.html +41 -0
- Documentation/urls.py +11 -0
- Documentation/views.py +442 -0
- LogstashUI/__init__.py +0 -0
- LogstashUI/__main__.py +10 -0
- LogstashUI/asgi.py +16 -0
- LogstashUI/cli.py +626 -0
- LogstashUI/config.py +116 -0
- LogstashUI/database.py +263 -0
- LogstashUI/insecure_http.py +117 -0
- LogstashUI/logging_config.py +99 -0
- LogstashUI/migrate_engine.py +282 -0
- LogstashUI/packaging/__init__.py +3 -0
- LogstashUI/packaging/logstashui.default +68 -0
- LogstashUI/packaging/logstashui.service.in +22 -0
- LogstashUI/paths.py +181 -0
- LogstashUI/settings.py +437 -0
- LogstashUI/telemetry.py +159 -0
- LogstashUI/urls.py +56 -0
- LogstashUI/wsgi.py +77 -0
- Management/__init__.py +0 -0
- Management/apps.py +10 -0
- Management/migrations/0001_initial.py +29 -0
- Management/migrations/0002_settings.py +25 -0
- Management/migrations/0003_settings_agent_ui_url.py +29 -0
- Management/migrations/0004_settings_logstash_artifact_base_url.py +29 -0
- Management/migrations/__init__.py +0 -0
- Management/models.py +92 -0
- Management/templates/api_tokens.html +214 -0
- Management/templates/components/api_token_created.html +38 -0
- Management/templates/components/api_token_row.html +84 -0
- Management/templates/components/logstash_artifact_row.html +100 -0
- Management/templates/components/logstash_artifact_tbody.html +26 -0
- Management/templates/components/user_row.html +67 -0
- Management/templates/logs.html +98 -0
- Management/templates/logstash_artifacts.html +172 -0
- Management/templates/management.html +80 -0
- Management/templates/management_settings.html +320 -0
- Management/templates/registration/login.html +404 -0
- Management/templates/users.html +304 -0
- Management/urls.py +23 -0
- Management/views.py +804 -0
- Monitoring/__init__.py +0 -0
- Monitoring/apps.py +9 -0
- Monitoring/migrations/__init__.py +0 -0
- Monitoring/static/js/monitoring.js +463 -0
- Monitoring/templates/components/node_metrics.html +161 -0
- Monitoring/templates/components/pipeline_metrics.html +189 -0
- Monitoring/templates/monitoring.html +271 -0
- Monitoring/urls.py +16 -0
- Monitoring/views.py +724 -0
- PipelineManager/__init__.py +0 -0
- PipelineManager/agent_api.py +1173 -0
- PipelineManager/agent_client.py +59 -0
- PipelineManager/agent_modes.py +880 -0
- PipelineManager/agent_policies.py +689 -0
- PipelineManager/agent_versions.py +151 -0
- PipelineManager/apps.py +10 -0
- PipelineManager/artifact_metrics.py +171 -0
- PipelineManager/artifacts.py +820 -0
- PipelineManager/connections_crud.py +722 -0
- PipelineManager/data/default_jvm.options +76 -0
- PipelineManager/data/default_log4j2.properties +165 -0
- PipelineManager/data/default_logstash.yml +405 -0
- PipelineManager/data/plugins.json +29109 -0
- PipelineManager/editor_views.py +608 -0
- PipelineManager/forms.py +284 -0
- PipelineManager/manager_views.py +490 -0
- PipelineManager/migrations/0001_initial.py +38 -0
- PipelineManager/migrations/0002_alter_connection_connection_type_and_more.py +38 -0
- PipelineManager/migrations/0003_policy_connection_policy.py +38 -0
- PipelineManager/migrations/0004_policy_current_revision_number_and_more.py +75 -0
- PipelineManager/migrations/0005_apikey_enrollmenttoken.py +38 -0
- PipelineManager/migrations/0006_enrollmenttoken_name.py +18 -0
- PipelineManager/migrations/0007_alter_enrollmenttoken_options_and_more.py +21 -0
- PipelineManager/migrations/0008_connection_agent_id.py +18 -0
- PipelineManager/migrations/0009_connection_last_check_in_policy_jvm_options_hash_and_more.py +33 -0
- PipelineManager/migrations/0010_keystore_revision_number_pipeline_revision_number.py +23 -0
- PipelineManager/migrations/0011_keystore_kv_hash.py +18 -0
- PipelineManager/migrations/0012_policy_binary_path.py +18 -0
- PipelineManager/migrations/0013_connection_status_blob.py +18 -0
- PipelineManager/migrations/0014_pipeline_pipeline_batch_delay_and_more.py +43 -0
- PipelineManager/migrations/0015_add_pipeline_hash.py +18 -0
- PipelineManager/migrations/0016_backfill_pipeline_hash.py +32 -0
- PipelineManager/migrations/0017_policy_keystore_password.py +31 -0
- PipelineManager/migrations/0018_policy_last_deployed_at.py +18 -0
- PipelineManager/migrations/0019_connection_restart_on_next_checkin.py +18 -0
- PipelineManager/migrations/0020_pipeline_no_input_pipeline_non_reloadable.py +23 -0
- PipelineManager/migrations/0021_connection_desired_agent_version.py +18 -0
- PipelineManager/migrations/0022_keystore_managed_by_pipeline_managed_by.py +23 -0
- PipelineManager/migrations/0023_agent_modes_policy_connection.py +89 -0
- PipelineManager/migrations/0024_seed_system_policies.py +173 -0
- PipelineManager/migrations/0025_packaged_managed_policy_types.py +166 -0
- PipelineManager/migrations/0026_normalize_opt_logstash_agent_paths.py +63 -0
- PipelineManager/migrations/0027_packaged_managed_default_ports.py +49 -0
- PipelineManager/migrations/0028_apikey_admin_tokens.py +80 -0
- PipelineManager/migrations/0029_logstash_artifacts.py +45 -0
- PipelineManager/migrations/0030_connection_allow_self_signed_certs.py +33 -0
- PipelineManager/migrations/0031_deploy_system_policies.py +93 -0
- PipelineManager/migrations/0032_connection_agent_inbound_key.py +30 -0
- PipelineManager/migrations/0033_simulation_result.py +26 -0
- PipelineManager/migrations/__init__.py +0 -0
- PipelineManager/models.py +1300 -0
- PipelineManager/pipelines_crud.py +738 -0
- PipelineManager/policies_crud.py +772 -0
- PipelineManager/sim_keystore.py +319 -0
- PipelineManager/simulation.py +1581 -0
- PipelineManager/static/css/codemirror.min.css +1 -0
- PipelineManager/static/css/graph_move.css +79 -0
- PipelineManager/static/css/monokai.min.css +1 -0
- PipelineManager/static/css/move_mode.css +144 -0
- PipelineManager/static/css/show-hint.min.css +1 -0
- PipelineManager/static/images/age.png +0 -0
- PipelineManager/static/images/aggregate.png +0 -0
- PipelineManager/static/images/alter.png +0 -0
- PipelineManager/static/images/azure_event_hubs.png +0 -0
- PipelineManager/static/images/beats.png +0 -0
- PipelineManager/static/images/boundary.png +0 -0
- PipelineManager/static/images/bytes.png +0 -0
- PipelineManager/static/images/cidr.png +0 -0
- PipelineManager/static/images/cipher.png +0 -0
- PipelineManager/static/images/circonus.png +0 -0
- PipelineManager/static/images/clone.png +0 -0
- PipelineManager/static/images/cloudwatch.png +0 -0
- PipelineManager/static/images/comment.png +0 -0
- PipelineManager/static/images/continue.png +0 -0
- PipelineManager/static/images/couchdb_changes.png +0 -0
- PipelineManager/static/images/csv.png +0 -0
- PipelineManager/static/images/datadog.png +0 -0
- PipelineManager/static/images/datadog_metrics.png +0 -0
- PipelineManager/static/images/date.png +0 -0
- PipelineManager/static/images/de_dot.png +0 -0
- PipelineManager/static/images/dead_letter_queue.png +0 -0
- PipelineManager/static/images/dissect.png +0 -0
- PipelineManager/static/images/dns.png +0 -0
- PipelineManager/static/images/drop.png +0 -0
- PipelineManager/static/images/dynatrace.png +0 -0
- PipelineManager/static/images/elapsed.png +0 -0
- PipelineManager/static/images/elastic_agent.png +0 -0
- PipelineManager/static/images/elastic_integration.png +0 -0
- PipelineManager/static/images/elastic_serverless_forwarder.png +0 -0
- PipelineManager/static/images/elastic_workplace_search.png +0 -0
- PipelineManager/static/images/elasticsearch.png +0 -0
- PipelineManager/static/images/else.png +0 -0
- PipelineManager/static/images/else_if.png +0 -0
- PipelineManager/static/images/email.png +0 -0
- PipelineManager/static/images/environment.png +0 -0
- PipelineManager/static/images/exec.png +0 -0
- PipelineManager/static/images/extractnumbers.png +0 -0
- PipelineManager/static/images/file.png +0 -0
- PipelineManager/static/images/fingerprint.png +0 -0
- PipelineManager/static/images/ganglia.png +0 -0
- PipelineManager/static/images/gelf.png +0 -0
- PipelineManager/static/images/generator.png +0 -0
- PipelineManager/static/images/geoip.png +0 -0
- PipelineManager/static/images/github.png +0 -0
- PipelineManager/static/images/google_bigquery.png +0 -0
- PipelineManager/static/images/google_cloud_storage.png +0 -0
- PipelineManager/static/images/google_pubsub.png +0 -0
- PipelineManager/static/images/graphite.png +0 -0
- PipelineManager/static/images/graphtastic.png +0 -0
- PipelineManager/static/images/grok.png +0 -0
- PipelineManager/static/images/heartbeat.png +0 -0
- PipelineManager/static/images/http.png +0 -0
- PipelineManager/static/images/http_poller.png +0 -0
- PipelineManager/static/images/i18n.png +0 -0
- PipelineManager/static/images/if.png +0 -0
- PipelineManager/static/images/imap.png +0 -0
- PipelineManager/static/images/influxdb.png +0 -0
- PipelineManager/static/images/irc.png +0 -0
- PipelineManager/static/images/java_generator.png +0 -0
- PipelineManager/static/images/java_stdin.png +0 -0
- PipelineManager/static/images/java_stdout.png +0 -0
- PipelineManager/static/images/java_uuid.png +0 -0
- PipelineManager/static/images/jdbc.png +0 -0
- PipelineManager/static/images/jdbc_static.png +0 -0
- PipelineManager/static/images/jdbc_streaming.png +0 -0
- PipelineManager/static/images/jms.png +0 -0
- PipelineManager/static/images/jmx.png +0 -0
- PipelineManager/static/images/json.png +0 -0
- PipelineManager/static/images/json_encode.png +0 -0
- PipelineManager/static/images/juggernaut.png +0 -0
- PipelineManager/static/images/kafka.png +0 -0
- PipelineManager/static/images/kinesis.png +0 -0
- PipelineManager/static/images/kv.png +0 -0
- PipelineManager/static/images/librato.png +0 -0
- PipelineManager/static/images/log4j.png +0 -0
- PipelineManager/static/images/loggly.png +0 -0
- PipelineManager/static/images/logstash.png +0 -0
- PipelineManager/static/images/lumberjack.png +0 -0
- PipelineManager/static/images/meetup.png +0 -0
- PipelineManager/static/images/memcached.png +0 -0
- PipelineManager/static/images/metriccatcher.png +0 -0
- PipelineManager/static/images/metricize.png +0 -0
- PipelineManager/static/images/metrics.png +0 -0
- PipelineManager/static/images/mongodb.png +0 -0
- PipelineManager/static/images/mutate.png +0 -0
- PipelineManager/static/images/nagios.png +0 -0
- PipelineManager/static/images/nagios_nsca.png +0 -0
- PipelineManager/static/images/opentsdb.png +0 -0
- PipelineManager/static/images/pagerduty.png +0 -0
- PipelineManager/static/images/pipe.png +0 -0
- PipelineManager/static/images/pipeline.png +0 -0
- PipelineManager/static/images/prune.png +0 -0
- PipelineManager/static/images/puppet_facter.png +0 -0
- PipelineManager/static/images/rabbitmq.png +0 -0
- PipelineManager/static/images/range.png +0 -0
- PipelineManager/static/images/redis.png +0 -0
- PipelineManager/static/images/redmine.png +0 -0
- PipelineManager/static/images/relp.png +0 -0
- PipelineManager/static/images/riak.png +0 -0
- PipelineManager/static/images/riemann.png +0 -0
- PipelineManager/static/images/rss.png +0 -0
- PipelineManager/static/images/ruby.png +0 -0
- PipelineManager/static/images/s3-sns-sqs.png +0 -0
- PipelineManager/static/images/s3.png +0 -0
- PipelineManager/static/images/salesforce.png +0 -0
- PipelineManager/static/images/sink.png +0 -0
- PipelineManager/static/images/sleep.png +0 -0
- PipelineManager/static/images/snmp.png +0 -0
- PipelineManager/static/images/snmptrap.png +0 -0
- PipelineManager/static/images/sns.png +0 -0
- PipelineManager/static/images/solr_http.png +0 -0
- PipelineManager/static/images/split.png +0 -0
- PipelineManager/static/images/sqlite.png +0 -0
- PipelineManager/static/images/sqs.png +0 -0
- PipelineManager/static/images/statsd.png +0 -0
- PipelineManager/static/images/stdin.png +0 -0
- PipelineManager/static/images/stdout.png +0 -0
- PipelineManager/static/images/stomp.png +0 -0
- PipelineManager/static/images/syslog.png +0 -0
- PipelineManager/static/images/syslog_pri.png +0 -0
- PipelineManager/static/images/tcp.png +0 -0
- PipelineManager/static/images/threats_classifier.png +0 -0
- PipelineManager/static/images/throttle.png +0 -0
- PipelineManager/static/images/timber.png +0 -0
- PipelineManager/static/images/tld.png +0 -0
- PipelineManager/static/images/translate.png +0 -0
- PipelineManager/static/images/truncate.png +0 -0
- PipelineManager/static/images/twitter.png +0 -0
- PipelineManager/static/images/udp.png +0 -0
- PipelineManager/static/images/unix.png +0 -0
- PipelineManager/static/images/urldecode.png +0 -0
- PipelineManager/static/images/useragent.png +0 -0
- PipelineManager/static/images/uuid.png +0 -0
- PipelineManager/static/images/varnishlog.png +0 -0
- PipelineManager/static/images/webhdfs.png +0 -0
- PipelineManager/static/images/websocket.png +0 -0
- PipelineManager/static/images/wmi.png +0 -0
- PipelineManager/static/images/wurfl_device_detection.png +0 -0
- PipelineManager/static/images/xml.png +0 -0
- PipelineManager/static/images/xmpp.png +0 -0
- PipelineManager/static/images/zabbix.png +0 -0
- PipelineManager/static/js/agent_inspect_modal.js +141 -0
- PipelineManager/static/js/agent_policies.js +3746 -0
- PipelineManager/static/js/agent_status_sse.js +166 -0
- PipelineManager/static/js/codemirror.min.js +1 -0
- PipelineManager/static/js/connections_table.js +551 -0
- PipelineManager/static/js/d3.v7.js +20625 -0
- PipelineManager/static/js/diff_modal.js +995 -0
- PipelineManager/static/js/expression_editor.js +291 -0
- PipelineManager/static/js/js-yaml.min.js +1 -0
- PipelineManager/static/js/logstashyml_guides.js +1063 -0
- PipelineManager/static/js/move_graph.js +577 -0
- PipelineManager/static/js/move_mode.js +559 -0
- PipelineManager/static/js/pipeline_editor.js +4102 -0
- PipelineManager/static/js/pipeline_graph_editor.js +3542 -0
- PipelineManager/static/js/pipeline_list.js +274 -0
- PipelineManager/static/js/pipeline_settings.js +121 -0
- PipelineManager/static/js/pipeline_text_editor.js +2088 -0
- PipelineManager/static/js/plugin_config_modal.js +2827 -0
- PipelineManager/static/js/policy_deploy_modal.js +1066 -0
- PipelineManager/static/js/show-hint.min.js +1 -0
- PipelineManager/static/js/sim_targets.js +380 -0
- PipelineManager/static/js/simple-comment-mode.js +56 -0
- PipelineManager/static/js/simulation_modal.js +1135 -0
- PipelineManager/static/js/simulation_results.js +2778 -0
- PipelineManager/static/js/stats_strip.js +231 -0
- PipelineManager/static/js/yaml.js +120 -0
- PipelineManager/system_policy_defaults.py +279 -0
- PipelineManager/templates/components/pipeline_editor/diff_modal.html +127 -0
- PipelineManager/templates/components/pipeline_editor/expression_editor.html +160 -0
- PipelineManager/templates/components/pipeline_editor/plugin_config_modal.html +119 -0
- PipelineManager/templates/components/pipeline_editor/plugin_modal.html +1016 -0
- PipelineManager/templates/components/pipeline_editor/simulation_modal.html +394 -0
- PipelineManager/templates/components/pipeline_editor/simulation_results.html +123 -0
- PipelineManager/templates/components/pipeline_editor/stats_strip.html +123 -0
- PipelineManager/templates/components/pipeline_editor/view_code_modal.html +133 -0
- PipelineManager/templates/components/pipeline_manager/agent_inspect_content.html +805 -0
- PipelineManager/templates/components/pipeline_manager/agent_inspect_modal.html +40 -0
- PipelineManager/templates/components/pipeline_manager/agent_policies.html +2421 -0
- PipelineManager/templates/components/pipeline_manager/change_policy_modal.html +210 -0
- PipelineManager/templates/components/pipeline_manager/collapsible_row.html +11 -0
- PipelineManager/templates/components/pipeline_manager/connection_modal.html +1361 -0
- PipelineManager/templates/components/pipeline_manager/keystore_modal.html +269 -0
- PipelineManager/templates/components/pipeline_manager/logstashyml_guides/centralized_pipeline_management.html +291 -0
- PipelineManager/templates/components/pipeline_manager/logstashyml_guides/default.html +166 -0
- PipelineManager/templates/components/pipeline_manager/mcp_modal.html +241 -0
- PipelineManager/templates/components/pipeline_manager/pipeline_list_content.html +586 -0
- PipelineManager/templates/components/pipeline_manager/policy_deploy_modal.html +238 -0
- PipelineManager/templates/pipeline_editor.html +1738 -0
- PipelineManager/templates/pipeline_graph_editor.html +99 -0
- PipelineManager/templates/pipeline_manager.html +584 -0
- PipelineManager/templates/pipeline_text_editor.html +350 -0
- PipelineManager/urls.py +99 -0
- SNMP/__init__.py +0 -0
- SNMP/ai_template_generation.py +232 -0
- SNMP/apps.py +9 -0
- SNMP/assets/device_template_generation/agents/snmp-profile-author.json +15 -0
- SNMP/assets/device_template_generation/skills/snmp-catalog.json +9 -0
- SNMP/data/authoring_instructions.md +65 -0
- SNMP/data/grounding/.gitignore +4 -0
- SNMP/data/grounding/build_grounding.py +35 -0
- SNMP/data/grounding/grounding.json +1 -0
- SNMP/data/grounding/sample_agent_payload.cisco2960x.json +2184 -0
- SNMP/data/mib_reference/std_bgp4_mib.json +43 -0
- SNMP/data/mib_reference/std_entity_sensors.json +28 -0
- SNMP/data/mib_reference/std_host_resources.json +32 -0
- SNMP/data/mib_reference/std_ospf_mib.json +55 -0
- SNMP/data/mib_reference/std_ucd_linux.json +27 -0
- SNMP/data/normalizers.json +103 -0
- SNMP/data/official_device_templates/arista_eos.json +24 -0
- SNMP/data/official_device_templates/aruba_wireless_controller.json +23 -0
- SNMP/data/official_device_templates/brocade_fc_switch.json +20 -0
- SNMP/data/official_device_templates/cisco_ios.json +21 -0
- SNMP/data/official_device_templates/default.json +13 -0
- SNMP/data/official_device_templates/dell_idrac.json +22 -0
- SNMP/data/official_device_templates/dell_x1026.json +16 -0
- SNMP/data/official_device_templates/dlink_dgs1210_switch.json +19 -0
- SNMP/data/official_device_templates/eastpower_ups.json +20 -0
- SNMP/data/official_device_templates/eaton_ups.json +22 -0
- SNMP/data/official_device_templates/epson_printer.json +18 -0
- SNMP/data/official_device_templates/geist_watchdog.json +20 -0
- SNMP/data/official_device_templates/generic_linux.json +18 -0
- SNMP/data/official_device_templates/generic_ont.json +18 -0
- SNMP/data/official_device_templates/generic_ups.json +16 -0
- SNMP/data/official_device_templates/hp_laserjet_mfp_m281cdw.json +18 -0
- SNMP/data/official_device_templates/hpe_nimble.json +17 -0
- SNMP/data/official_device_templates/huawei_ups.json +19 -0
- SNMP/data/official_device_templates/ingrasys_ups.json +19 -0
- SNMP/data/official_device_templates/isilon_onefs.json +22 -0
- SNMP/data/official_device_templates/mellanox_sx6036.json +20 -0
- SNMP/data/official_device_templates/netapp_7mode.json +22 -0
- SNMP/data/official_device_templates/palo_alto_firewall.json +21 -0
- SNMP/data/official_device_templates/phoenixtec_ups.json +18 -0
- SNMP/data/official_device_templates/ubiquiti_unifi_ap.json +19 -0
- SNMP/data/official_device_templates/ubiquiti_unifi_switch.json +18 -0
- SNMP/data/official_device_templates/ubiquiti_unifi_udm.json +19 -0
- SNMP/data/official_device_templates/versa_flexvnf_appliance.json +19 -0
- SNMP/data/official_profiles/arista_eos.json +16 -0
- SNMP/data/official_profiles/aruba_wireless_controller.json +145 -0
- SNMP/data/official_profiles/brocade_fibre_channel_switch_fibre_channel_ports.json +35 -0
- SNMP/data/official_profiles/brocade_fibre_channel_switch_name_server.json +23 -0
- SNMP/data/official_profiles/brocade_fibre_channel_switch_system_metrics.json +36 -0
- SNMP/data/official_profiles/cisco_cdp.json +26 -0
- SNMP/data/official_profiles/cisco_fans.json +18 -0
- SNMP/data/official_profiles/cisco_sensors.json +21 -0
- SNMP/data/official_profiles/cisco_system_metrics.json +40 -0
- SNMP/data/official_profiles/dell_idrac_cpu.json +19 -0
- SNMP/data/official_profiles/dell_idrac_fans.json +20 -0
- SNMP/data/official_profiles/dell_idrac_global_status.json +13 -0
- SNMP/data/official_profiles/dell_idrac_memory.json +20 -0
- SNMP/data/official_profiles/dell_idrac_power_supply.json +19 -0
- SNMP/data/official_profiles/dell_idrac_raid_controller.json +19 -0
- SNMP/data/official_profiles/dlink_dgs1210.json +15 -0
- SNMP/data/official_profiles/dlink_dgs1210_system_metrics.json +38 -0
- SNMP/data/official_profiles/eaton_ups.json +40 -0
- SNMP/data/official_profiles/geist_environment.json +50 -0
- SNMP/data/official_profiles/generic_arp.json +19 -0
- SNMP/data/official_profiles/generic_bgp.json +24 -0
- SNMP/data/official_profiles/generic_entity_psu.json +26 -0
- SNMP/data/official_profiles/generic_entity_sensor.json +22 -0
- SNMP/data/official_profiles/generic_host_system_metrics.json +68 -0
- SNMP/data/official_profiles/generic_interfaces.json +86 -0
- SNMP/data/official_profiles/generic_ip_addr.json +19 -0
- SNMP/data/official_profiles/generic_lldp.json +54 -0
- SNMP/data/official_profiles/generic_lm_sensors.json +37 -0
- SNMP/data/official_profiles/generic_mac_table.json +19 -0
- SNMP/data/official_profiles/generic_ont.json +88 -0
- SNMP/data/official_profiles/generic_ospf.json +21 -0
- SNMP/data/official_profiles/generic_printer_mib.json +48 -0
- SNMP/data/official_profiles/generic_rmon.json +38 -0
- SNMP/data/official_profiles/generic_system.json +17 -0
- SNMP/data/official_profiles/generic_ucd_system_metrics.json +63 -0
- SNMP/data/official_profiles/generic_ups_mib.json +154 -0
- SNMP/data/official_profiles/hpe_nimble_volumes.json +59 -0
- SNMP/data/official_profiles/huawei_ups.json +111 -0
- SNMP/data/official_profiles/isilon_performance.json +92 -0
- SNMP/data/official_profiles/isilon_protocols.json +77 -0
- SNMP/data/official_profiles/isilon_system.json +86 -0
- SNMP/data/official_profiles/mellanox_mlnx_os.json +15 -0
- SNMP/data/official_profiles/netapp_7mode_data_protection.json +106 -0
- SNMP/data/official_profiles/netapp_7mode_disks.json +51 -0
- SNMP/data/official_profiles/netapp_7mode_protocols.json +66 -0
- SNMP/data/official_profiles/netapp_7mode_system.json +92 -0
- SNMP/data/official_profiles/netapp_7mode_volumes.json +166 -0
- SNMP/data/official_profiles/paloalto_components.json +36 -0
- SNMP/data/official_profiles/paloalto_system.json +15 -0
- SNMP/data/official_profiles/traps.json +16 -0
- SNMP/data/official_profiles/ubiquiti_unifi_switch.json +18 -0
- SNMP/data/official_profiles/ubiquiti_unifi_switch_system.json +14 -0
- SNMP/data/official_profiles/ubiquiti_unifi_wireless.json +60 -0
- SNMP/data/official_profiles/versa_flexvnf.json +14 -0
- SNMP/data/schema.md +650 -0
- SNMP/data/schema_reference/snmp_field_schema.md +747 -0
- SNMP/data/snmp_template.json +629 -0
- SNMP/data/template_profile_context.md +3986 -0
- SNMP/inline_grounding.py +77 -0
- SNMP/management/__init__.py +1 -0
- SNMP/management/commands/__init__.py +1 -0
- SNMP/management/commands/generate_template_profile_context.py +272 -0
- SNMP/management/commands/load_test_snmp_data.py +240 -0
- SNMP/management/commands/sync_snmp_official_data.py +263 -0
- SNMP/management/commands/unload_test_snmp_data.py +77 -0
- SNMP/migrations/0001_initial.py +101 -0
- SNMP/migrations/0002_devicetemplate.py +34 -0
- SNMP/migrations/0003_remove_devicetemplate_type_remove_profile_type_and_more.py +31 -0
- SNMP/migrations/0004_device_device_template.py +19 -0
- SNMP/migrations/0005_devicetemplate_product_profile_product.py +23 -0
- SNMP/migrations/0006_alter_devicetemplate_model_and_more.py +28 -0
- SNMP/migrations/0007_remove_device_profiles.py +17 -0
- SNMP/migrations/0008_devicetemplate_type.py +18 -0
- SNMP/migrations/0009_alter_device_device_template.py +19 -0
- SNMP/migrations/0010_alter_device_device_template.py +19 -0
- SNMP/migrations/0011_network_namespace.py +18 -0
- SNMP/migrations/0012_profile_normalizers.py +18 -0
- SNMP/migrations/0013_snmpdeploymentstate.py +26 -0
- SNMP/migrations/0014_alter_snmpdeploymentstate_last_config_change.py +18 -0
- SNMP/migrations/0015_alter_snmpdeploymentstate_last_config_change.py +20 -0
- SNMP/migrations/0016_alter_snmpdeploymentstate_last_config_change.py +18 -0
- SNMP/migrations/0017_remove_network_logstash_name.py +17 -0
- SNMP/migrations/0018_add_official_key.py +39 -0
- SNMP/migrations/0019_network_namespace_from_device_template.py +18 -0
- SNMP/migrations/0020_device_hostname_alter_device_ip_address_and_more.py +27 -0
- SNMP/migrations/0021_device_building_device_latitude_device_longitude_and_more.py +43 -0
- SNMP/migrations/0022_alter_device_latitude_alter_device_longitude.py +23 -0
- SNMP/migrations/0023_network_agent_connection_network_deployment_mode_and_more.py +30 -0
- SNMP/migrations/0024_network_credential_mode.py +18 -0
- SNMP/migrations/0025_network_ssl_certificate_authorities.py +18 -0
- SNMP/migrations/__init__.py +0 -0
- SNMP/models.py +892 -0
- SNMP/network_map.py +660 -0
- SNMP/overview.py +394 -0
- SNMP/snmp_crud.py +6082 -0
- SNMP/snmp_grounding.py +146 -0
- SNMP/snmp_normalizers.py +594 -0
- SNMP/snmp_pipeline_generator.py +1658 -0
- SNMP/snmp_test.py +962 -0
- SNMP/static/css/snmp.css +33 -0
- SNMP/static/images/apc.png +0 -0
- SNMP/static/images/arista.png +0 -0
- SNMP/static/images/aruba.png +0 -0
- SNMP/static/images/brocade.png +0 -0
- SNMP/static/images/cisco.png +0 -0
- SNMP/static/images/dell.png +0 -0
- SNMP/static/images/dlink.png +0 -0
- SNMP/static/images/east.png +0 -0
- SNMP/static/images/eaton.png +0 -0
- SNMP/static/images/epson.png +0 -0
- SNMP/static/images/hauwei.png +0 -0
- SNMP/static/images/hp.png +0 -0
- SNMP/static/images/hpe.png +0 -0
- SNMP/static/images/ingrasys.png +0 -0
- SNMP/static/images/linux.png +0 -0
- SNMP/static/images/mellanox.png +0 -0
- SNMP/static/images/netapp.png +0 -0
- SNMP/static/images/paloalto.png +0 -0
- SNMP/static/images/phoenixtec.png +0 -0
- SNMP/static/images/ubiquiti.png +0 -0
- SNMP/static/images/unknown.png +0 -0
- SNMP/static/images/versa.png +0 -0
- SNMP/static/images/vertiv.png +0 -0
- SNMP/static/js/ai_device_template_modal.js +1116 -0
- SNMP/static/js/credentials_table.js +291 -0
- SNMP/static/js/devices_table.js +588 -0
- SNMP/static/js/discovered_devices.js +291 -0
- SNMP/static/js/network_map.js +1657 -0
- SNMP/static/js/networks_table.js +360 -0
- SNMP/static/js/onboarding.js +866 -0
- SNMP/static/js/overview.js +416 -0
- SNMP/static/js/snmp_changes_indicator.js +76 -0
- SNMP/static/js/snmp_commit_modal.js +39 -0
- SNMP/static/js/snmp_credentials_modal.js +217 -0
- SNMP/static/js/snmp_device_template_modal.js +669 -0
- SNMP/static/js/snmp_device_visual_preview.js +1707 -0
- SNMP/static/js/snmp_devices_modal.js +912 -0
- SNMP/static/js/snmp_diff_modal.js +1559 -0
- SNMP/static/js/snmp_network_modal.js +940 -0
- SNMP/static/js/snmp_profile_modal.js +1212 -0
- SNMP/static/js/snmp_profile_modal_helpers.js +17 -0
- SNMP/static/js/snmp_test.js +538 -0
- SNMP/templates/Credentials.html +325 -0
- SNMP/templates/DeviceTemplates.html +1059 -0
- SNMP/templates/Devices.html +274 -0
- SNMP/templates/Networks.html +469 -0
- SNMP/templates/Onboarding.html +521 -0
- SNMP/templates/Overview.html +227 -0
- SNMP/templates/components/ai_device_template_modal.html +46 -0
- SNMP/templates/components/ai_generate_template_content.html +224 -0
- SNMP/templates/components/device_template_profile_modal.html +60 -0
- SNMP/templates/components/discovered_devices_content.html +86 -0
- SNMP/templates/components/discovered_devices_modal.html +43 -0
- SNMP/templates/components/gmaps_latlon_modal.html +93 -0
- SNMP/templates/components/network_map.html +110 -0
- SNMP/templates/components/snmp_commit_modal.html +53 -0
- SNMP/templates/components/snmp_credentials_modal.html +189 -0
- SNMP/templates/components/snmp_device_modal.html +6 -0
- SNMP/templates/components/snmp_device_template_modal.html +129 -0
- SNMP/templates/components/snmp_device_visual_preview.html +347 -0
- SNMP/templates/components/snmp_devices_modal.html +330 -0
- SNMP/templates/components/snmp_diff_modal.html +148 -0
- SNMP/templates/components/snmp_network_modal.html +380 -0
- SNMP/templates/components/snmp_profile_modal.html +147 -0
- SNMP/templates/components/snmp_test_modal.html +398 -0
- SNMP/templatetags/__init__.py +0 -0
- SNMP/templatetags/snmp_extras.py +17 -0
- SNMP/urls.py +94 -0
- SNMP/views.py +913 -0
- Site/__init__.py +0 -0
- Site/apps.py +9 -0
- Site/migrations/__init__.py +0 -0
- Site/product_ca_views.py +41 -0
- Site/static/images/ElasticIcon.png +0 -0
- Site/static/images/LoggyIcon.png +0 -0
- Site/static/images/LoggyWizardIcon.png +0 -0
- Site/static/images/LogstashAgentIcon.png +0 -0
- Site/static/images/LogstashIcon.png +0 -0
- Site/static/js/base.js +192 -0
- Site/static/js/marked.min.js +69 -0
- Site/templates/base.html +52 -0
- Site/templates/error.html +65 -0
- Site/templates/home.html +148 -0
- Site/templates/navigation.html +530 -0
- Site/templates/popup.html +251 -0
- Site/templatetags/__init__.py +0 -0
- Site/templatetags/custom_filters.py +36 -0
- Site/urls.py +21 -0
- Site/views.py +200 -0
- Utilities/__init__.py +0 -0
- Utilities/apps.py +9 -0
- Utilities/data/grok-patterns/LICENSE +202 -0
- Utilities/data/grok-patterns/ecs-v1/aws +33 -0
- Utilities/data/grok-patterns/ecs-v1/bacula +53 -0
- Utilities/data/grok-patterns/ecs-v1/bind +13 -0
- Utilities/data/grok-patterns/ecs-v1/bro +30 -0
- Utilities/data/grok-patterns/ecs-v1/exim +26 -0
- Utilities/data/grok-patterns/ecs-v1/firewalls +111 -0
- Utilities/data/grok-patterns/ecs-v1/grok-patterns +95 -0
- Utilities/data/grok-patterns/ecs-v1/haproxy +40 -0
- Utilities/data/grok-patterns/ecs-v1/httpd +17 -0
- Utilities/data/grok-patterns/ecs-v1/java +34 -0
- Utilities/data/grok-patterns/ecs-v1/junos +13 -0
- Utilities/data/grok-patterns/ecs-v1/linux-syslog +16 -0
- Utilities/data/grok-patterns/ecs-v1/maven +1 -0
- Utilities/data/grok-patterns/ecs-v1/mcollective +4 -0
- Utilities/data/grok-patterns/ecs-v1/mongodb +7 -0
- Utilities/data/grok-patterns/ecs-v1/nagios +124 -0
- Utilities/data/grok-patterns/ecs-v1/postgresql +2 -0
- Utilities/data/grok-patterns/ecs-v1/rails +13 -0
- Utilities/data/grok-patterns/ecs-v1/redis +3 -0
- Utilities/data/grok-patterns/ecs-v1/ruby +2 -0
- Utilities/data/grok-patterns/ecs-v1/squid +6 -0
- Utilities/data/grok-patterns/ecs-v1/zeek +33 -0
- Utilities/data/grok-patterns/legacy/aws +14 -0
- Utilities/data/grok-patterns/legacy/bacula +50 -0
- Utilities/data/grok-patterns/legacy/bind +3 -0
- Utilities/data/grok-patterns/legacy/bro +13 -0
- Utilities/data/grok-patterns/legacy/exim +19 -0
- Utilities/data/grok-patterns/legacy/firewalls +91 -0
- Utilities/data/grok-patterns/legacy/grok-patterns +95 -0
- Utilities/data/grok-patterns/legacy/haproxy +39 -0
- Utilities/data/grok-patterns/legacy/httpd +15 -0
- Utilities/data/grok-patterns/legacy/java +17 -0
- Utilities/data/grok-patterns/legacy/junos +9 -0
- Utilities/data/grok-patterns/legacy/linux-syslog +16 -0
- Utilities/data/grok-patterns/legacy/maven +1 -0
- Utilities/data/grok-patterns/legacy/mcollective +1 -0
- Utilities/data/grok-patterns/legacy/mcollective-patterns +4 -0
- Utilities/data/grok-patterns/legacy/mongodb +7 -0
- Utilities/data/grok-patterns/legacy/nagios +124 -0
- Utilities/data/grok-patterns/legacy/postgresql +3 -0
- Utilities/data/grok-patterns/legacy/rails +13 -0
- Utilities/data/grok-patterns/legacy/redis +3 -0
- Utilities/data/grok-patterns/legacy/ruby +2 -0
- Utilities/data/grok-patterns/legacy/squid +4 -0
- Utilities/dissect.py +302 -0
- Utilities/grok.py +412 -0
- Utilities/migrations/__init__.py +0 -0
- Utilities/static/css/debugger_editor.css +88 -0
- Utilities/static/js/debugger_editor.js +93 -0
- Utilities/static/js/grok_debugger.js +131 -0
- Utilities/templates/dissect_debugger.html +95 -0
- Utilities/templates/grok_debugger.html +99 -0
- Utilities/urls.py +14 -0
- Utilities/views.py +363 -0
- logstashui-0.5.5.dev0.dist-info/METADATA +333 -0
- logstashui-0.5.5.dev0.dist-info/RECORD +762 -0
- logstashui-0.5.5.dev0.dist-info/WHEEL +4 -0
- logstashui-0.5.5.dev0.dist-info/entry_points.txt +2 -0
- logstashui-0.5.5.dev0.dist-info/licenses/LICENSE.txt +93 -0
- logstashui-0.5.5.dev0.dist-info/licenses/NOTICE.txt +2772 -0
- theme/__init__.py +0 -0
- theme/apps.py +9 -0
- theme/package-lock.json +6 -0
- theme/static/css/dist/styles.css +2 -0
- theme/static/images/favicon.ico +0 -0
- theme/static_src/.gitignore +1 -0
- theme/static_src/package-lock.json +1930 -0
- theme/static_src/package.json +26 -0
- theme/static_src/postcss.config.js +7 -0
- theme/static_src/src/styles.css +38 -0
- theme/static_src/tailwind.config.js +43 -0
- 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)
|