Skip to content

Application visibility in the raw flow partitions: Cisco NBAR2 and vendor equivalents (continues #295) - #297

Open
TheWitness wants to merge 44 commits into
developfrom
feature/cisco-nbar-reports
Open

TheWitness wants to merge 44 commits into
developfrom
feature/cisco-nbar-reports

Conversation

@TheWitness

@TheWitness TheWitness commented Oct 19, 2026 •

Copy link
Copy Markdown
Member

Application visibility for FlowView: Cisco NBAR2 and vendor equivalents (continues #295)

This PR continues @alcatron's #295 (now closed) on the same branch name, keeping all of his commits and attribution. On top of the earlier maintainer refactor, it reworks how applications are collected. #295 and the first version of this PR ran a second NetFlow v9 parser and stored a separate copy of every application flow. Now application identity flows through FlowView's single template engine and is stored with every flow in the raw partitions. Every report, filter and summary is materialized from those partitions.

63 files changed against the previous head of this PR (7f099b6). The README's Application Visibility section is the user-facing documentation.


1. One template engine, applications stored with every flow

  • No second parser. includes/nbar_collector.php re-parsed every v9 packet with its own template cache. It is removed. flow_collector.php follows the v9 and IPFIX template stream of every exporter, including Options Templates, and decodes the application from the same record as the addresses and counters (includes/flow_templates.php).
  • app_id in the raw partitions. Every plugin_flowview_raw_* partition has an integer app_id column, added last, so MariaDB 10.3+ and MySQL 8.0.12+ add it instantly with ALGORITHM=INSTANT. Partitions created before the upgrade read as "no application" until they get the column.
  • Application dictionary. The new plugin_flowview_applications table holds one row per application: the vendor namespace, an optional per-exporter scope, the vendor's own key, and the name, description and category. Names that arrive later never rewrite flows.
  • Recognised templates. A template carrying an application shows as Supported (Application) in the template viewer.
  • Reports and filters. There is a new Application statistical report and an Applications filter, which matches names across vendors (*webex*) or ids. Changing either re-materializes the Filter, like any other Filter change.
  • NBAR reports read the raw partitions. The Cisco Apps (NBAR) hourly and daily summaries are built from the raw partitions, rebuilt when late flows arrive, and can be rebuilt on demand while the partitions are retained (--rebuild-summaries).

2. Vendor application mapping

Vendor Where the application comes from Names Effort
Cisco NBAR2 IE 95, RFC 6759 engine and selector Application Options Template (learned) Easy
ntop nProbe L7_PROTO/L7_PROTO_NAME (v9 57590/57591, IPFIX 35632.118/119) In the flow record Easy
Palo Alto PAN-OS v9 field 56701 (App-ID name, no number) In the flow record Easy, with caveats
Citrix NetScaler 5951.151 plus 5951.150, per appliance AppName map 5951.152 (learned) Moderate
Fortinet FortiGate IE 95: engine 20, PEN 12356, FortiGuard id Options Template 257 (learned) Moderate
Citrix SD-WAN IE 95/96 (RFC 6759 proprietary engines) IE 96 Moderate: set the profile
Juniper SRX IE 95 holding a 4 byte AppID (not RFC 6759) Not exported: import them Challenging
SonicWall 8741.22 Static Applications table via Table/Column Map (learned) Challenging
IANA engines (L3, L4, EtherType, LLC) IE 95 engines 1, 3, 18, 19 The host's protocol and service databases None
  • Per-stream Application Profile. Each stream has an Application Profile (Auto Detect, a vendor, or Ignore) in the Listener's Inbound Streams, or set with --profile. Auto Detect works the vendor out from the template fields and values, and shows what it detected.
  • No bundled catalogs. No vendor catalogs are bundled, since they are licensed and change with every signature update. cli/flowview_applications.php --import reads catalogs you produce from your own devices: Cisco show ip nbar protocol-id, Juniper show services application-identification application summary, nDPI ndpi_protocol_ids.h, or CSV. --scope applies Juniper custom ids to one exporter.
  • README coverage. The README covers each vendor step by step: exporter setup, what FlowView does, what the operator does, which vendors are harder and why, and how to compare one application across vendors.

3. Upgrade path for #295 and #297 installs

Checked against #295's head (d1e4bb1): its single plugin_flowview_nbar_data table, plugin_flowview_nbar_names and the summary tables with hex app_id match what the upgrade converts. #295 stores bin2hex() of field 95. #295 sets flowview_nbar_schema_version to 2 and this PR expects 3, so the background upgrade launches even though both are plugin version 5.1.

The background upgrade (cli/flowview_upgrade.php, guarded by register_process_start):

  1. moves the names into the dictionary;
  2. converts the hourly and daily summaries from hex ids to dictionary ids. The conversion is resumable: a retry never reads already-converted ids as hex again;
  3. adds app_id to the live partition and to the partitions of hours not summarised yet;
  4. copies applications from the legacy tables onto the raw flows of those hours. Hours that can't be rebuilt with their applications keep their converted summaries;
  5. stops writing the legacy tables and expires them with the NBAR retention. The Add Cisco NBAR application reports with reusable history summaries #295 table is emptied in batches.

Every #295 file this PR removes is tombstoned in manifest.json, so the upgrade deletes it.

Operator options (cli/flowview_applications.php):

  • --backfill-from-nbar [--start --end] [--add-column] copies the legacy applications onto older raw flows and re-materializes the affected Filters. It then drops each legacy table it copied completely; --keep-legacy keeps them.
  • --drop-legacy removes every legacy table immediately, whatever the migration state. It keeps the NBAR summaries and the progress table of their conversion.

4. Locks

There is no GET_LOCK() anywhere in the plugin any more. Partition alters, engine conversion, the app_id column add, the NBAR summary, daily and observation workers, the NBAR page count, the shared live-partition scan, and the legacy NBAR tables all register a flowview task in Cacti's process registry (register_process_start) through includes/locks.php. That registry is InnoDB with a unique task key, so the locks hold across cluster nodes and failovers. On top of it, includes/locks.php adds:

  • an optional wait;
  • re-taking a lock the process already holds;
  • releasing every lock when the process ends, even on a fatal error;
  • timeouts well beyond the work, because the registry kills a holder that outlives its timeout.

5. Command line scripts moved to cli/

Operator scripts live in cli/ without the flowview_ prefix, and they now change to the Cacti directory through __DIR__. The old chdir('../../') only worked when run from the plugin directory; the new form works from anywhere. The old paths are tombstoned in manifest.json, so the upgrade removes them. Update any cron entries that call them.

Before After
flowview_upgrade_nat_columns.php cli/upgrade_nat_columns.php
flowview_bulkarin.php cli/bulkarin.php
flowview_cleanup.php cli/cleanup.php
flowview_drop_raw_tables.php cli/drop_raw_tables.php
cli/flowview_upgrade.php cli/upgrade.php
cli/flowview_applications.php cli/applications.php
irr_tables.php (a schema script, not a CLI) includes/irr_tables.php, flowview_create_irr_tables()
  • Kept at the root: the poller and service entry points, which are launched by absolute path: flow_collector.php, flowview_process.php, flowview_runner.php and run_schedule.php.
  • includes/irr_tables.php: it now describes its 18 registry tables as data instead of 18 copies of one CREATE TABLE. The statements it runs are identical, token for token, to the old file's for Aria, InnoDB and MyISAM.
  • Shared argument handling: cli/cleanup.php and cli/drop_raw_tables.php read --proceed, --version and --help through one flowview_cli_proceed().

6. Bug fixes

In the template engine and collector:

  • The IPFIX enterprise number was read at the wrong offset.
  • NetFlow v9 wrongly treated the high bit of a field type as the IPFIX enterprise bit.
  • Templates were keyed by exporter address only. They are now keyed by listener, exporter, source id or observation domain, and template id.
  • IE 95 was discarded and Options Templates were skipped.
  • $allfields[96] (applicationName) was decoded as an unsigned8 instead of a string.
  • flowview_template_supported() could report an incomplete template as supported.
  • The NBAR report passed a string to get_timespan(), and first_weekdayid was not cast to int.

Found while moving the command line scripts. Both also exist on develop:

  • The upgrade checked reports_log for sent_by with the table and column swapped, so it dropped the scheduled report log every time it ran.
  • flowview_drop_raw_tables.php listed the raw partitions in the FlowView database but dropped them through Cacti's connection, so it did nothing when the flow tables are in a separate database. cli/cleanup.php now drops only its own database's map tables.

From @somethingwithproof's reviews:

Finding Status
Blocker: NBAR ignores Hostname Resolution (and the DNS timeout; it used the Mail/Reporting servers on method 0; it rewrote cached names as DNS) Fixed: method 2 resolves nothing, method 1 uses those servers, method 0 the host's resolvers, the DNS timeout setting is used, and cache writes are INSERT IGNORE
Blocker: external <script src> without the CSP nonce; url_path unescaped Fixed, plus a security test that every script tag has the nonce
PHP floor not stated Fixed: the README and INFO state PHP 8.1 (CI tests 8.2 to 8.6)
Double decode of every v9 record; app_id width Fixed by design: one engine, integer app_id; IE 95 over 32 bytes is rejected
Daily build at REPEATABLE READ Fixed: READ COMMITTED, as the hourly build already was
Connections fallback without a time limit Fixed: it runs under a statement time limit through fv_nbar_bounded_select(), and is reported unavailable where the server can't bound it
MySQL 9.x page totals Fixed: any MySQL from 8.0
Leftover #295 table Fixed: migrated, backfilled, expired, droppable
README placement and "listener permissions" wording; MySQL consequence for daily summaries Fixed
Upgrade ignores a busy alter Fixed: logged
Dead $nbar_earliest, $return_url and its JS handlers Removed
SonarCloud Green
Blocker: shard cache treats "not the newest table" as cold and validates only by MIN/MAX Open. Exists on develop; not introduced here
Partition discovery not schema scoped; stale session table bounds; Filters planned four times; running-ALTER guard needs PROCESS; sleep(2) in a request; unpinned 8.6 PPA Open. All exist on develop; not introduced here

Related: #349 fixes a separate develop bug where single-threaded reports (flowview_parallel_threads = 1) dropped the Filter and date range.

7. Evidence

  • CI on ce5e488: integration tests on PHP 8.2 to 8.6, translations and SonarCloud all pass.
  • Unit tests: 760 pass (4,016 assertions). Patch coverage is 100% of the 2,503 changed production lines against develop (tests/bin/patch-coverage.php). New suites: FlowTemplateTest, ApplicationDecodeTest, NbarUpgradeTest, LocksTest, IrrTablesTest, CliProceedTest, plus rewrites of the NBAR partition, worker and request tests.
  • Static analysis: PHPStan levels 6 and 8 report nothing new in the changed code.
  • Live MariaDB 10.5 runs (scratch databases, outside the repository):
    1. Ingest: Cisco, Fortinet, Juniper and Palo Alto packets through the collector to app_id, the dictionary, the summaries and the reports.
    2. Upgrade from the Application visibility in the raw flow partitions: Cisco NBAR2 and vendor equivalents (continues #295) #297 and Add Cisco NBAR application reports with reusable history summaries #295 schemas: names, summaries, backfill, expiry, and a rerun.
    3. Interrupted upgrade: a summary conversion stopped between steps is resumed without inventing applications or losing rows. Pending hours whose partitions can't carry applications keep their summaries.
    4. Legacy tables: backfill, then drop what was copied; forced drop; both refused while another process holds them.
    5. Locks on Cacti 1.2.x's real lib/poller.php with the InnoDB registry: of 8 racing processes exactly one wins, waiters get the lock once it is released, a fatal error releases it, and a dead holder's registration is taken over.

8. Known limitations

  • SonicWall: its own flow template (257) is not translated into flows, so only templates with IANA addresses and 8741.22 are classified.
  • Fortinet: the layout follows Fortinet's documentation and RFC 6759; it has not been checked against a capture.
  • Juniper: exports no names (import them), and its first custom ids can look like IANA protocols until the stream is known to be Juniper (set the profile).
  • MySQL: daily NBAR summaries are never built (no max_statement_time), so long ranges read hourly summaries. MySQL 8 was not tested live.
  • Multi-host installs: Cacti's process registry judges liveness by local PID, so on several Cacti hosts sharing one database, one host can take over another's live lock. Single-host installs with an HA database are fine.

alcatron and others added 25 commits October 18, 2026 16:16
…equires)

- Move the pure-library nbar_*.php files into includes/ and drop their request guards; phpunit.xml coverage includes follow them.
- Move the non-poller, non-service CLI (flowview_upgrade.php) into cli/ and fix its chdir depth, callers, manifest tombstone and patch-coverage allowlist.
- Hoist mid-file require/include statements to the top of each file and parenthesise every require/include path.
- Add parameter and return types to every function and method this PR adds.
- Format css/nbar.css and js/nbar-*.js with tabs.
- Drop the obsolete direct-request guard scenarios for files that no longer carry guards.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…type test stubs

- php-cs-fixer with Cacti develop's rules (echo->print, spacing, blank lines, alignment) over every file this PR adds; for pre-existing files only the lines this PR added are touched.
- Regenerate locales/po/cacti.pot (xgettext step only): same msgids, updated file references for the moved files.
- Type the Pest/DNS/report stub functions and classes in the new tests.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
plugin_flowview_check_upgrade() runs on every page load while an upgrade is pending, so each request could spawn another background upgrade. Launch it only when register_process_start() succeeds (four hour timeout). cli/flowview_upgrade.php releases that lock, and its own run lock, however it ends (early exit, success, or fatal error via a shutdown function); its own registration timeout drops from 24 hours to 4 hours to match.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…ngs in NBAR code

- Replace count()/sizeof() with cacti_count()/cacti_sizeof() in production code (Net/ excluded); add a cacti_count stub to the unit bootstrap.
- Narrow-width fv_nbar_int() for NetFlow header fields; typed/guarded results for unpack, preg_split, inet_pton/inet_ntop, hex2bin, json_encode, parse_url.
- Declare variables inherited by the included report fragments, initialise by-reference arguments, and pass correctly typed html_start_box() arguments.
- Remove an always-true condition in fv_section_params().

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Guard array|bool database results with is_array() before use as arrays (flowview.php, flowview_schedules.php, run_schedule.php, includes/database.php, includes/functions-pre13.php).
- Initialise the by-reference report tag as a bool for reports_load_format_file().
- Pass the message level to raise_message_javascript() as its level argument instead of as the message body.
- Keep the Query Service request body a string; document the by-reference output text parameter as a string.
- Add regression tests for the changed measured lines and allowlist the pre-1.3 compatibility shim in the patch-coverage gate.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…s in includes/database.php

The NBAR schema was built by five layers: a generic definition builder (includes/nbar_database.php), fv_nbar_summary_schema(), fv_nbar_daily_schema(), fv_nbar_seen_schema() and fv_nbar_exporter_schema(), orchestrated by fv_nbar_schema_install(). The layers created tables and then patched them with ALTER TABLE and seed inserts to reach the final shape.

Replace all of that with flowview_db_create_nbar_tables() in includes/database.php: one CREATE TABLE IF NOT EXISTS per table in the same format as flowview_setup_table(), each verified after creation. Verified against a real MariaDB: the 11 tables are identical, column for column and key for key, to what the old chain produced (the only difference is a table comment on each).

Remove includes/nbar_database.php and the schema installers. NBAR has not shipped, so no deprecation shims are kept, and the ALTER/seed steps that only repaired tables from earlier development revisions of this branch are gone. Tests are rewritten against the new function.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Raw NBAR records now go to plugin_flowview_nbar_data_<year><day>[<hour>]
tables, following the Database Partitioning Scheme setting (hourly by
default, daily when set to daily), the same way the raw flow tables are
partitioned.

- Slices are created when the first record for them arrives and are
  named by UTC time so the repeated daylight saving hour cannot share a
  table.
- Readers list the existing slices and test each slice's time range, so
  slices from before a scheme change keep working.
- The summary, daily, connection, seen and feed status readers build a
  UNION ALL of per-slice selects, each with the same filter, and fall
  back to an empty typed relation when no slice exists yet.
- Retention drops whole expired slices instead of deleting rows.
- The collector batches rows per slice and writes them together with the
  hour revision bump in one transaction.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…HANGELOG order

The NBAR report built "d.listener_id IN ()" when no enabled capture
device existed, which is a SQL error.  Capture ids start at 1, so the
scope now uses IN (0) and matches nothing.

CHANGELOG.md is restored to the develop ordering and wording so the PR
no longer rewrites unrelated entries; only the NBAR feature entries are
added.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings October 19, 2026 21:42

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved data-correctness, process-ownership, and query-scaling issues prevent safe approval.

4 open issues
What changed in this PR

Continues #295 by adding Cisco NBAR application reporting to FlowView, with partitioned history and background maintenance.

Changes:

  • Adds application, conversation, and connection reports with account-specific preferences.
  • Introduces time-sliced storage, reusable summaries, retention, and supervised maintenance.
  • Expands regression coverage and updates compatibility handling and documentation.
File Description
tests/​Unit/​PreexistingCodeGuardsTest.php Tests legacy compatibility fixes.
tests/​Unit/​NbarWorkerDeadlineTest.php Tests worker supervision and deadlines.
tests/​Unit/​NbarTemplateCacheTest.php Tests template-cache limits.
tests/​Unit/​NbarSessionCacheTest.php Tests account-scoped caches.
tests/​Unit/​NbarSchemaTest.php Tests NBAR schema creation.
tests/​Unit/​NbarReviewRegressionTest.php Covers database and reporting regressions.
tests/​Unit/​NbarReportRequestTest.php Tests report request handling.
tests/​Unit/​NbarReportPageTest.php Tests report rendering and empty captures.
tests/​Unit/​NbarRenderingTest.php Tests escaping and report presentation.
tests/​Unit/​NbarLatestReviewTest.php Tests timespans, status, and cleanup.
tests/​Unit/​NbarFailurePathsTest.php Tests failure handling.
tests/​Unit/​NbarDnsTest.php Tests bounded DNS resolution.
tests/​Unit/​NbarDirectRequestTest.php Tests direct-access guards.
tests/​Unit/​NbarDailyWorkerTest.php Tests summary maintenance.
tests/​Unit/​NbarCountRequestTest.php Tests deferred count requests.
tests/​Unit/​NbarConnectionPagingTest.php Tests exact connection pagination.
tests/​Unit/​NbarBoundaryTest.php Tests summary and input boundaries.
tests/​Unit/​NbarBehaviorTest.php Tests decoding and report behavior.
tests/​Unit/​NbarBackfillTest.php Tests observation-date backfills.
tests/​Unit/​CspNonceTest.php Checks script nonce spacing.
tests/​helpers/​request.php Adds isolated request execution.
tests/​fixtures/​nbar-report-request.php Supplies report request scenarios.
tests/​fixtures/​nbar-dns-budget.php Isolates DNS budget testing.
tests/​fixtures/​nbar-direct-request.php Exercises direct-access guards.
tests/​fixtures/​nbar-count-request.php Supplies deferred-count scenarios.
tests/​bootstrap-unit.php Extends configurable test doubles.
tests/​bin/​patch-coverage.php Updates coverage exclusions.
setup.php Integrates schema, retention, and maintenance.
run_schedule.php Guards failed report lookups.
README.md Documents NBAR operation and limitations.
phpunit.xml Includes NBAR coverage targets.
nbar_setup_guide.php Adds Cisco configuration guidance.
nbar_conversations.php Renders conversation reports.
manifest.json Tracks new and relocated files.
js/​nbar-tables.js Adds sorting, resizing, and pagination.
js/​nbar-setup-guide.js Handles setup-dialog dismissal.
js/​nbar-report.js Handles report navigation and timespans.
js/​nbar-preferences.js Applies capture and display preferences.
includes/​nbar_timespan.php Bounds report timespans by retention.
includes/​nbar_seen.php Handles observation dates and backfills.
includes/​nbar_query.php Adds cached queries and paging SQL.
includes/​nbar_partition.php Manages raw history slices.
includes/​nbar_feed_status.php Displays capture freshness.
includes/​nbar_dns.php Adds bounded DNS caching.
includes/​nbar_count.php Implements deferred exact counts.
includes/​nbar_common.php Provides retention and worker helpers.
includes/​nbar_chart.php Renders application-volume charts.
includes/​functions.php Corrects legacy helper usage.
includes/​functions-pre13.php Hardens older-core report handling.
flowview.php Routes NBAR reports and requests.
flowview_upgrade_nat_columns.php Updates the upgrade-path comment only.
flowview_sections.php Adds saved report-section navigation.
flowview_schedules.php Guards failed log lookups.
flowview_devices.php Corrects error-message arguments.
flow_collector.php Integrates NBAR and reduced-width decoding.
css/​nbar.css Styles NBAR reports and dialogs.
cli/​flowview_upgrade.php Relocates upgrades and adds maintenance modes.
CHANGELOG.md Records NBAR features.
.github/​copilot-instructions.md Updates documented upgrade paths.

Review effort: Balanced

Comment thread includes/nbar_count.php Resolved
Comment thread includes/nbar_partition.php Resolved
Comment thread includes/nbar_partition.php Resolved
Comment thread setup.php Resolved
…upgrade launch

- A failed SHOW TABLES for the raw NBAR slices is no longer an empty
  list.  fv_nbar_data_tables() throws, so hourly builds roll back instead
  of publishing an empty hour, retention skips the pass, the first/latest
  record lookups report failure, and the report shows an error instead of
  treating the history as missing.
- The first/latest record lookup probes the slices in batches of 32
  rather than one query per slice, so a capture with no records costs a
  handful of queries instead of one per retained slice.
- The deferred connection count stores its selection criteria and
  rebuilds its source when it runs, so a slice created after the page
  rendered is included.  The cache key is derived from the criteria.
- The upgrade CLI takes over the launcher's process registration, so a
  timeout recovery can only signal the upgrade and never a reused web
  worker.
- The test bootstrap exec_background() stub now has Cacti's real
  signature; the two-argument stub made static analysis flag the
  plugin's three-argument calls.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
The merge brought fv_nbar_timespan_options() into includes/nbar_timespan.php,
but the only caller is the isolated report page, whose scenarios never drive a
preset whose window exactly equals the retention window, leaving the
duplicate-period continue (nbar_timespan.php:49) uncovered and failing the
100%% changed-line coverage gate.

Add an optional \[__test_get_timespan] override to the bootstrap
get_timespan stub (default fixed window unchanged) and a direct unit test that
drives presets inside, exactly on, before, and after the retention window,
covering the keep, drop-duplicate, and exclude branches plus both retention
labels.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

@somethingwithproof somethingwithproof left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This covers the delta since aedac47 (now ca19214), excluding locale files. These commits don't touch the earlier NBAR findings, so their status comes first, then the new items.

Earlier findings, still open at ca19214

  • Blocker: NBAR ignores "Hostname Resolution = Don't Resolve DNS". includes/nbar_dns.php still never reads flowview_dns_method or settings_dns_timeout.
  • Blocker: the external <script src> tags have no nonce: nbar_report.php:299-301, includes/nbar_preferences.php:191, nbar_setup_guide.php:99. nbar_report.php:300 also prints url_path unescaped.
  • Partly fixed: the PHP floor. CI is now 8.2 to 8.6 and everything lints on 8.1, but INFO still says compat = 1.2.29 and the README does not state the floor.
  • Still open, unchanged: READ COMMITTED for the daily build, the double v9 decode and app_id width, the unbounded Connections fallback, MySQL 9.x page totals, the leftover #295 table, the README placement and "subject to listener permissions" wording, and the dead $nbar_earliest / $return_url.

New findings

Blocker: the shard cache treats "not the newest table name" as finished, and validates only by MIN/MAX bounds.
includes/functions.php:5059 (flowview_get_cold_partitions), :4486 (flowview_shard_cache_is_current), :5742 (flowview_materialize_rotated_partitions).
The collector picks the partition from the exporter's timestamp (flow_collector.php get_sql_prefix($flowtime)).

  • An exporter whose clock is ahead creates a future-named table. The partition still taking flows then becomes "cold" and is materialized and cached while it is still being written.
  • Exporters with slightly behind clocks keep writing the previous partition after the poller sees the new table and launches materialization. The cache check compares only MIN(start_time) and MAX(end_time), so rows that land inside those bounds leave stale totals in the cache until the bounds happen to move.
    Please validate cached shards with a cheap content signal such as COUNT(*) and SUM(bytes) stored with the shard, and delay materializing a rotated partition by a grace period.

Suggestion: partition discovery is not schema-scoped. includes/functions.php:4869 (flowview_get_partition_tables) and :2792 (get_tables_for_query) read information_schema.TABLES without TABLE_SCHEMA = DATABASE(), unlike flowview_get_pending_partition_alters. A restored copy of the database on the same server puts foreign plugin_flowview_raw_* tables in the list. They can become "newest", which breaks the cold/live split, and the unqualified FROM $table queries then fail.

Suggestion: session-cached table bounds go stale after rotation. includes/functions.php:2816-2825 keeps each table's MIN/MAX in $_SESSION. A table first seen while live keeps a stale max_date once it rotates, so flowview_is_full_scan can classify a range ending between the stale and real max as a full scan. That includes rows past the range end and can read a cached full-partition shard.

Suggestion: the Filters page plans every filter four times per load. flowview_filters.php:487 and :547. flowview_get_filter_md5sums runs per filter, and again for every filter inside flowview_get_shard_cache_summary. Each pass re-reads the query row and re-requires arrays.php, and flowview_get_cached_shard_tables adds a grouped shard-cache query per filter per mode. Compute the keys once per request.

Suggestion: the upgrade ignores a busy result. cli/flowview_upgrade.php:578. With FLOWVIEW_ALTER_LOCK_WAIT = 7200 the upgrade can block 2 hours per table, then carry on with the table un-upgraded and no log line. Log it or fail.

Suggestion: the running-ALTER guard depends on PROCESS. includes/functions.php:5367 reads information_schema.PROCESSLIST, which shows only your own threads without the PROCESS privilege. Without it the "wait for ALTER" logic in the materializer and the engine converter does nothing. A fallback such as a metadata-lock probe, or a documented privilege requirement, would cover it.

Nit: flowview_filters.php:152 sleep(2) in a web request.
Nit: the 8.6 leg installs from ppa:ondrej/php unpinned. It is non-blocking, so this is only worth a comment.

SonarCloud Code Analysis is failing (Reliability Rating on new code) and needs to be green. The workflow itself looks fine: pull_request only, read-only token, actions pinned by SHA.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>
Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

@somethingwithproof somethingwithproof left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The blockers from the 2026-11-12 review are still open at 7f099b6. The commits since ca19214 are the develop merge and the timeout-message fix, and none of them touch this code.

  • Blocker: NBAR ignores "Hostname Resolution = Don't Resolve DNS". includes/nbar_dns.php still never reads flowview_dns_method or settings_dns_timeout.
  • Blocker: these <script src> tags still have no nonce: nbar_report.php:299-301, includes/nbar_preferences.php:191 and nbar_setup_guide.php:99. Under the core nonce CSP, nbar-tables.js is blocked on a full page load. nbar_report.php:300 also still prints url_path unescaped.
  • Blocker: the shard cache still treats any partition that isn't the newest table name as cold, and it validates cached shards only by MIN/MAX bounds. The clock-skew cases are in the earlier review.
  • INFO still says compat = 1.2.29, and the README still doesn't state the PHP floor.

The timeout-message change in 7f099b6 is fine. 1.2.x's raise_message_javascript() takes three parameters and ignores the fourth.

TheWitness and others added 2 commits December 5, 2026 09:28
Rework the NBAR support of #295/#297 so application identity follows the
single v9/IPFIX template engine instead of a second parser.

- Store an integer app_id in every raw flow partition, keyed into a new
  plugin_flowview_applications dictionary (namespace, scope, key, name)
- Decode applications in the template stream for Cisco NBAR2 (IE95/96 and
  the options names template), Fortinet, Juniper, Palo Alto, SonicWall,
  ntop/nProbe and Citrix, with per stream Application Profiles
- Fix the IPFIX enterprise number offset, the v9 enterprise bit, and key
  templates by listener, exporter, domain and template id
- Build the NBAR summaries from the raw partitions, so a changed Filter or
  a late flow is materialized again from the raw data
- Add the Application statistics report and an applications Filter field
- Upgrade the #295/#297 schema: map the hexadecimal ids to the dictionary,
  convert the summaries resumably, backfill raw flows from the legacy
  slices, keep the summaries of hours that can not be rebuilt, and expire
  the legacy slices with the NBAR retention
- Add cli/flowview_applications.php to list, import catalogs, set profiles,
  add the column, backfill and rebuild summaries
- Document application visibility per vendor in the README

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Comment thread flow_collector.php Fixed
Comment thread includes/applications.php Fixed
Comment thread includes/applications.php Fixed
Comment thread tests/Unit/FlowTemplateTest.php Fixed
TheWitness and others added 2 commits December 5, 2026 10:28
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Keep the serialized state itself rather than its md5, and read the
collector field table in the tests without eval.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
TheWitness and others added 2 commits December 5, 2026 14:35
Replace GET_LOCK() across the plugin with leases in the new InnoDB table
plugin_flowview_locks.  GET_LOCK() lives on one database server, so it is
not shared by Galera nodes or a proxy spreading connections over them and
is lost on a failover, and the processes table behind register_process
is a MEMORY table that Galera does not replicate.

- A lease is one conditional write (INSERT IGNORE, or an UPDATE of an
  expired lease or of the token read), and its affected row count decides
  the winner, so certification settles races and no read replica can make
  two processes think they hold it
- Leases expire on the database clock; the lease of an exited process of
  the same host is taken over at once; every lease is released when its
  process ends, even on a fatal error
- Used for partition alters and engine conversions, the app_id column,
  the NBAR summary, daily and observation workers, the NBAR page count,
  the live partition scan, and the legacy NBAR tables

flowview_applications.php --backfill-from-nbar now drops each legacy NBAR
table it copied completely (unless --keep-legacy), and --drop-legacy drops
every legacy table at once whatever its migration status, keeping the
NBAR summaries and the progress of their conversion.  The upgrade, the
backfill, the drops and the expiry of the legacy tables take turns under
one lease.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Cacti keeps the processes table in InnoDB with a unique task key, so
register_process_start() admits one process per task across the nodes of
a database cluster.  The locks of includes/locks.php are now flowview
tasks in that registry instead of leases in plugin_flowview_locks.

- flowview_lock_acquire() registers lock_<name> (shortened to a hash past
  the registry's 40 characters), waits for it when asked, and lets the
  process that holds it take it again
- flowview_lock_release() unregisters only this process's registration,
  and every lock is released when the process ends, even on a fatal error
- the timeouts stay far beyond the work they guard, as the registry
  retires a holder that outlives its timeout
- the upgrade drops plugin_flowview_locks of the earlier build

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Comment thread includes/locks.php Fixed
Comment thread tests/Unit/LocksTest.php Fixed
Comment thread tests/Unit/LocksTest.php Fixed
Comment thread tests/Unit/LocksTest.php Fixed
TheWitness and others added 3 commits December 5, 2026 15:06
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Walk through how each vendor's application reaches the app_id column,
what the operator configures on the exporter and in FlowView, which
vendors are more challenging and why, and how to compare one
application across vendors.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- NBAR DNS follows Hostname Resolution: no lookups when it is Don't
  Resolve, the Mail/Reporting/DNS servers only when it says so, the DNS
  timeout setting, and INSERT IGNORE so a cached name from FlowView's own
  resolver or ARIN is never replaced
- Every external NBAR script tag has the CSP nonce, url_path is escaped,
  and a security test checks every script tag for the nonce
- The daily summary build reads at READ COMMITTED, so a late flow never
  waits on its shared locks
- The deep Connections fallback runs under the same statement time limit
  as the page count, through a shared fv_nbar_bounded_select(), and the
  page count works on MySQL 9 and later
- IE 95 values longer than 32 bytes are not application ids
- The upgrade logs a partition it could not alter because another
  process held it
- Remove the unused $nbar_earliest and return link code
- README: state PHP 8.1, move the NBAR sections above Possible Bugs and
  the footer, correct the access wording and the stale template cache
  text, and note that MySQL never builds daily summaries; the setup
  guide no longer says IPFIX application records are not decoded

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@TheWitness TheWitness changed the title Add Cisco NBAR application reports with partitioned storage (continues #295) Application visibility in the raw flow partitions: Cisco NBAR2 and vendor equivalents (continues #295) Dec 5, 2026
TheWitness and others added 2 commits December 5, 2026 16:52
- flowview_upgrade_nat_columns.php, flowview_bulkarin.php,
  flowview_cleanup.php and flowview_drop_raw_tables.php are now
  cli/upgrade_nat_columns.php, cli/bulkarin.php, cli/cleanup.php and
  cli/drop_raw_tables.php, and change to the Cacti directory from
  __DIR__, so they run from any directory instead of only the plugin's
- cli/flowview_upgrade.php and cli/flowview_applications.php are now
  cli/upgrade.php and cli/applications.php
- irr_tables.php, a schema script setup.php and the upgrade included, is
  now includes/irr_tables.php with flowview_create_irr_tables()
- The old paths are tombstoned in manifest.json, so the upgrade removes
  them; the README, CHANGELOG, help texts, messages and the developer
  notes name the new paths

The poller and service entry points stay where they are: flow_collector.php,
flowview_process.php, flowview_runner.php and run_schedule.php.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- includes/irr_tables.php describes its 18 registry tables as data (a
  column catalog and each table's columns, keys and comment) instead of
  18 copies of the same CREATE TABLE; the statements it runs are the
  same, token for token, for Aria, InnoDB and MyISAM
- cli/cleanup.php and cli/drop_raw_tables.php read --proceed, --version
  and --help through one flowview_cli_proceed()
- The upgrade checked reports_log for sent_by with the table and column
  swapped, so it dropped the scheduled report log on every run
- cli/drop_raw_tables.php listed the raw partitions in the FlowView
  database but dropped them through Cacti's connection; it now drops them
  in the FlowView database, and cli/cleanup.php only drops the map tables
  of its own database

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@sonarqubecloud

sonarqubecloud Bot commented Dec 5, 2026

Copy link
Copy Markdown

@somethingwithproof somethingwithproof left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requesting changes. Reviewed at the current head (after 87917bf). Fresh install and upgrade from develop give the same schema on MariaDB 10.11 and MySQL 8.4 (apart from column position), the report pages validate their inputs, and the NetFlow v9/IPFIX parsing loops always advance with bounds-checked reads. Still open:

  1. Blocker (from my earlier review): includes/nbar_dns.php never reads flowview_dns_method, so NBAR resolves DNS even with "Don't Resolve DNS" set.
  2. Blocker (from my earlier review): external <script src> tags have no CSP nonce: nbar_report.php:299-301, includes/nbar_preferences.php:191, nbar_setup_guide.php:99. nbar_report.php:300 also prints url_path unescaped; wrap it in plugin_flowview_escape_attr.
  3. The Applications filter is ignored when Max Concurrent Threads is Disabled (the single-threaded path, fixed by #349). Seen live on both databases. Merge #349 first and add a single-thread Applications-filter test here.
  4. MySQL never builds daily summaries or the observation-date backfill (includes/nbar_common.php:107-118, includes/nbar_daily.php:112-118, includes/nbar_seen.php:95-98): both depend on MariaDB's max_statement_time. Reports fall back to hourly summaries, so it's speed rather than correctness; use MAX_EXECUTION_TIME on MySQL or document it.
  5. The applications dictionary only grows: flowview_app_lookup adds a row per distinct identity seen in packets and nothing deletes them. Consider a cap or retention for learned rows, and bound flowview_app_learn_sonicwall's per-exporter maps (includes/applications.php:557).
  6. The description is stale: it still describes plugin_flowview_nbar_data_* tables, which 87917bf stopped writing (includes/nbar_partition.php:38).
  7. INFO still says compat = 1.2.29 and the README doesn't state the PHP floor.

Nits: after an upgrade the applications column sits in a different position than on a fresh install (includes/nbar_upgrade.php:57 vs setup.php:1310); two tests in ApplicationDecodeTest.php (29, 145) need the host's /etc/protocols and /etc/services.

One further collector-side point I'll send you separately.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants