diff --git a/CHANGELOG.md b/CHANGELOG.md index 48cc1456..56101ef8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ --- develop --- +* feature: Add a manually importable Linux recommendation catalogue in docs/linux.json.gz with the 102 entries of systemd's journal message catalog (v262.2), keyed on the journal MESSAGE_ID that rsyslog or syslog-ng forwarders can append to the message; contrib/recommendations/extract_systemd_catalog.py converts the catalog for build_catalogues.py, and devices whose sysDescr or template mentions Linux but no network vendor are now recognised as Linux for recommendation scoping * dev: Sync js/cards.js with the Cacti core Card API controller (Cacti/cacti#8928): defer a card refresh until an in-flight grow or shrink settles so it no longer reverts the resize, target drops by row start so a taller card no longer captures a drop in a later row and a dragged card alone in its row no longer jumps up a row, and bind the add-card control once so a re-initialised grid receives added cards * issue#491: Syslog Status no longer fails with "Undefined constant SYSLOG_COLLECTOR_STALE_SECONDS" (and Cacti no longer disables the plugin) when Collector Staleness Threshold or Collector Backlog Threshold is set to Default; both defaults (300 seconds, 10000 messages) are now defined in `includes/functions.php` before the Status tab is drawn * issue#484: Mark the syslog search help string in `syslog.php` as `no-php-format` and update `locales/po/cacti.pot` so the literal `%` in `LIKE` syntax is not flagged as a PHP format specifier diff --git a/README.md b/README.md index 14c7af3b..b93e3860 100644 --- a/README.md +++ b/README.md @@ -807,7 +807,10 @@ which returns JSON. name different vendors, or any of them is unrecognised, the host is treated as unrecognised. The recognised vendors use the names of the bundled catalogues: Arista, Cisco, Dell, Fortinet, HPE, Huawei, Juniper, MikroTik, - Nokia, NVIDIA and Palo Alto Networks. + Nokia, NVIDIA and Palo Alto Networks. A device that names none of them but + mentions Linux in its description or template (a Net-SNMP agent reports + `Linux ...`) is a Linux device. Many network operating + systems run on Linux, so a vendor named in either always wins. * When several recommendations match, the longest identifiers are shown first, up to three. * Identifiers containing other characters, such as the `#` slot placeholder or @@ -863,11 +866,53 @@ lists the source documents, versions and retrieval dates of each file, and | `docs/fortinet.json.gz` | Fortinet | 1,462 | FortiOS 7.6.8 Log Message Reference, every traffic, event and UTM log ID as the 10-digit `logid` sent on the wire (`logid="0100032001"`). The full ID is built from the documented type, subtype and message ID. Fortinet documents no recommended actions. | | `docs/paloalto.json.gz` | Palo Alto Networks | 364 | PAN-OS System log event IDs from the Syslog Severity Reference, such as `tunnel-status-down`. Generic event IDs (`general`, `auth`) and event IDs that are ordinary networking phrases other vendors also log (`link-down`, `admin-down`, `auth-fail`, `lacp-up`) are excluded. Few records have a recommended action. | | `docs/mikrotik.json.gz` | MikroTik | 11 | RouterOS has no message IDs and MikroTik publishes no message catalogue; only documented messages that carry a distinctive word are included (for example `hashtype`, `auto-initialization`, `hw-limit`, `bpdu-guard`, `CTSYNC`, `deassigned`). | +| `docs/linux.json.gz` | Linux | 102 | systemd's journal message catalog (systemd v262.2), keyed on the 32-digit hexadecimal journal `MESSAGE_ID`, such as `be02cf6855d2428ba40df7e9d022f03d` for a failed unit start. Covers units, PID 1, journald, logind, core dumps, the OOM killer, shutdown and time changes. Only matches when the forwarder appends the ID; see [Linux and systemd message IDs](#linux-and-systemd-message-ids). | Numeric identifiers, such as HPE event IDs, Fortinet log IDs and FRRouting error codes, only match messages from a Cacti device whose vendor is recognised (see the matching rules above). +### Linux and systemd message IDs + +Plain syslog does not carry the journal's `MESSAGE_ID`, so the Linux catalogue +only matches when the sending host's forwarder reads the journal and appends +the ID to the message text as ` MESSAGE_ID=`. Configure this on each Linux +host that forwards to Cacti, not on the Cacti collector. Messages without an ID +are forwarded unchanged. + +rsyslog, with the `imjournal` input (Red Hat family distributions load it by +default; do not load it twice): + +```console +module(load="imjournal" StateFile="imjournal.state") + +template(name="CactiJournal" type="string" + string="<%PRI%>%TIMESTAMP% %HOSTNAME% %syslogtag%%msg:::sp-if-no-1st-sp%%msg% MESSAGE_ID=%$!MESSAGE_ID%") + +if $!MESSAGE_ID != "" then { + action(type="omfwd" target="cacti.example.com" port="514" protocol="udp" template="CactiJournal") +} else { + action(type="omfwd" target="cacti.example.com" port="514" protocol="udp" template="RSYSLOG_TraditionalForwardFormat") +} +``` + +syslog-ng, with the `systemd-journal()` source: + +```console +source s_journal { systemd-journal(); }; +destination d_cacti { + network("cacti.example.com" port(514) transport("udp") + template("<${PRI}>${DATE} ${HOST} ${MSGHDR}${MESSAGE}$(if (\"${.journald.MESSAGE_ID}\" ne \"\") \" MESSAGE_ID=${.journald.MESSAGE_ID}\" \"\")\n")); +}; +log { source(s_journal); destination(d_cacti); }; +``` + +Both examples were checked with rsyslog 8.2604 and syslog-ng 3.35. A forwarded +failed unit start then reads +`systemd[1]: Failed to start nginx.service - A high performance web server. MESSAGE_ID=be02cf6855d2428ba40df7e9d022f03d`. +`journalctl -x` shows the same catalogue text on the host itself, and +`journalctl -o verbose` shows the `MESSAGE_ID` of an entry. + The file picker accepts `.json` and `.json.gz`; pasted JSON is also supported. Exports (selected rows or the current filters) download as `.json.gz` by default. Gzip import and export require PHP's zlib extension. Both the compressed file diff --git a/contrib/recommendations/build_catalogues.py b/contrib/recommendations/build_catalogues.py index b3092408..9e42fdeb 100755 --- a/contrib/recommendations/build_catalogues.py +++ b/contrib/recommendations/build_catalogues.py @@ -22,7 +22,9 @@ the plugin's docs/ directory. Usage: build_catalogues.py VENDOR < extracted/.json - VENDOR is one of: arista dell fortinet hpe huawei mikrotik nokia nvidia paloalto + VENDOR is one of: arista dell fortinet hpe huawei linux mikrotik nokia nvidia paloalto + +For linux, the extracted JSON comes from extract_systemd_catalog.py. """ import gzip @@ -33,7 +35,7 @@ # Output names are taken from this table, never from the command line. VENDORS = {name: name for name in - ('arista', 'dell', 'fortinet', 'hpe', 'huawei', 'mikrotik', 'nokia', 'nvidia', 'paloalto')} + ('arista', 'dell', 'fortinet', 'hpe', 'huawei', 'linux', 'mikrotik', 'nokia', 'nvidia', 'paloalto')} DOCS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), 'docs') diff --git a/contrib/recommendations/extract_systemd_catalog.py b/contrib/recommendations/extract_systemd_catalog.py new file mode 100755 index 00000000..2da56480 --- /dev/null +++ b/contrib/recommendations/extract_systemd_catalog.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +# +-------------------------------------------------------------------------+ +# | Copyright (C) 2004-2026 The Cacti Group | +# | | +# | This program is free software; you can redistribute it and/or | +# | modify it under the terms of the GNU General Public License | +# | as published by the Free Software Foundation; either version 2 | +# | of the License, or (at your option) any later version. | +# | | +# | This program is distributed in the hope that it will be useful, | +# | but WITHOUT ANY WARRANTY; without even the implied warranty of | +# | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | +# | GNU General Public License for more details. | +# +-------------------------------------------------------------------------+ +"""Convert a systemd journal message catalog into syslog-recommendations JSON. + +The input is a catalog source file in the format documented at +https://systemd.io/CATALOG/, such as systemd's catalog/systemd.catalog.in. +Only untranslated entries (no locale after the message ID) are converted. +Each MESSAGE_ID becomes the identifier, the Subject the message and the +prose payload the explanation; an entry without prose uses its Subject as the +explanation. The output is the input of build_catalogues.py linux. + +Usage: extract_systemd_catalog.py REFERENCE_URL < systemd.catalog.in > linux.json +""" + +import io +import json +import re +import sys + +SEPARATOR = re.compile(r'^-- ([0-9a-f]{32})(?: (\S+))?\s*$') +HEADER = re.compile(r'^([A-Za-z][A-Za-z-]*):\s*(.*)$') + + +def entries(lines): + entry = None + + for line in lines: + line = line.rstrip('\n') + + if line.startswith('#'): + continue + + match = SEPARATOR.match(line) + + if match: + if entry is not None: + yield entry + entry = {'id': match.group(1), 'locale': match.group(2), 'headers': [], 'body': [], 'in_body': False} + continue + + if entry is None: + continue + + if not entry['in_body']: + if line.strip() == '': + entry['in_body'] = True + continue + + header = HEADER.match(line) + + if header: + entry['headers'].append((header.group(1), header.group(2).strip())) + continue + + entry['body'].append(line) + + if entry is not None: + yield entry + + +def paragraphs(lines): + """Join the 76-column wrapped prose into paragraphs separated by blank lines.""" + out, current = [], [] + + for line in lines + ['']: + if line.strip() == '': + if current: + out.append(' '.join(current)) + current = [] + else: + current.append(line.strip()) + + return '\n\n'.join(out) + + +def convert(source, reference): + records = [] + + for entry in entries(source): + if entry['locale']: + continue + + headers = entry['headers'] + first = {name: value for name, value in reversed(headers)} + subject = first.get('Subject', '') + docs = [value for name, value in headers if name == 'Documentation' and value] + # Some entries, mostly fatal PID 1 errors, have a Subject and no prose. + text = paragraphs(entry['body']) or (subject.rstrip('.') + '.' if subject else '') + + if docs: + text += '\n\nDocumentation: ' + ', '.join(docs) + + records.append({ + 'vendor': 'Linux', + 'identifier': entry['id'], + 'component': first.get('Defined-By', 'systemd'), + 'severity': None, + 'message': subject, + 'explanation': text, + 'recommended_action': '', + 'reference': reference, + }) + + return {'format': 'syslog-recommendations', 'version': 1, 'recommendations': records} + + +def main(argv): + if len(argv) != 2: + sys.stderr.write(__doc__) + return 2 + + data = convert(io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8'), argv[1]) + json.dump(data, sys.stdout, indent=2, ensure_ascii=False) + sys.stdout.write('\n') + + return 0 + + +if __name__ == '__main__': + sys.exit(main(sys.argv)) diff --git a/docs/RECOMMENDATION_SOURCES.md b/docs/RECOMMENDATION_SOURCES.md index fdc09c40..a3529e65 100644 --- a/docs/RECOMMENDATION_SOURCES.md +++ b/docs/RECOMMENDATION_SOURCES.md @@ -18,6 +18,7 @@ Catalogues that are not covered by this build: The final step is `contrib/recommendations/build_catalogues.py`. It is run once per vendor, with the extracted JSON on standard input (`build_catalogues.py hpe < hpe.json`), and writes `docs/.json.gz`. +For Linux, `contrib/recommendations/extract_systemd_catalog.py` produces the extracted JSON (see [Linux](#linux)). For each vendor it: 1. Reads the extracted `.json` (envelope `{"format":"syslog-recommendations","version":1,"recommendations":[...]}`). @@ -198,6 +199,44 @@ had 5,578 records: the build drops the 694 without a description and one case-on - `FECD/5/PARITY ERROR` was skipped because its mnemonic contains a space. - Lines with a format version other than `%%01`, or without the `%%dd` header, will not match. +## Linux + +**Records: 102** (systemd's own journal messages: units and jobs, PID 1, journald, logind sessions and seats, +core dumps, the OOM killer, sleep and shutdown, time and time zone changes, resolved DNSSEC, machined, the +watchdog, TPM and portable services). + +| Document | Release | License | URL | Retrieved | +|---|---|---|---|---| +| systemd journal message catalog (`catalog/systemd.catalog.in`) | systemd v262.2 | LGPL-2.1-or-later | https://github.com/systemd/systemd/blob/v262.2/catalog/systemd.catalog.in | 2026-12-03 | +| Journal Message Catalogs (catalog format) | current | | https://systemd.io/CATALOG/ | 2026-12-03 | + +Build: + +```shell +curl -fsSL https://raw.githubusercontent.com/systemd/systemd/v262.2/catalog/systemd.catalog.in -o systemd.catalog.in +contrib/recommendations/extract_systemd_catalog.py \ + https://github.com/systemd/systemd/blob/v262.2/catalog/systemd.catalog.in < systemd.catalog.in > linux.json +contrib/recommendations/build_catalogues.py linux < linux.json +``` + +- **Identifier:** the journal `MESSAGE_ID`, 32 lower-case hexadecimal digits. Plain syslog does not carry it, so + the sending host's forwarder must append it to the message as `MESSAGE_ID=` (see Linux and systemd + message IDs in the README). For example, + `Dec 3 10:46:17 web01 systemd[1]: Failed to start nginx.service - A high performance web server. MESSAGE_ID=be02cf6855d2428ba40df7e9d022f03d` + gives `be02cf6855d2428ba40df7e9d022f03d`. +- **Fields:** `message` is the entry's `Subject`, `component` its `Defined-By` (`systemd` for every record) and + `explanation` its prose with the 76-column line wrapping joined into paragraphs. `Documentation` headers are + appended to the explanation. `severity` is `null` because catalog entries have no priority, and + `recommended_action` is empty because systemd puts any advice in the prose. +- **Gaps and notes:** + - `@FIELD@` placeholders, such as `@UNIT@` or `@COREDUMP_PID@`, are journal field names that `journalctl -x` + fills in. They are kept as published. + - 20 entries, mostly fatal PID 1 errors such as `Init received fatal signal and dumped core`, have a Subject + but no prose. Their Subject is used as the explanation. + - Only the English entries are used. The catalog's translations (`systemd..catalog.in`) are not. + - Catalogs shipped by other packages in `/usr/lib/systemd/catalog/`, such as dbus-broker's, are not included. + - Most Linux services (sshd, the kernel, postfix and so on) log without a `MESSAGE_ID`, so they are not covered. + ## MikroTik **Records: 11.** MikroTik publishes no catalogue of RouterOS log messages, and RouterOS has no message IDs. diff --git a/docs/linux.json.gz b/docs/linux.json.gz new file mode 100644 index 00000000..e26077bd Binary files /dev/null and b/docs/linux.json.gz differ diff --git a/includes/recommendations.php b/includes/recommendations.php index 9da9a623..4415dfb5 100644 --- a/includes/recommendations.php +++ b/includes/recommendations.php @@ -525,7 +525,8 @@ function syslog_recommendation_candidates(string $message): array { /** * Name the catalogue vendor of a Cacti device from its SNMP sysDescr or, when - * that names no recognised vendor, its device template name. + * that names no recognised vendor, its device template name. A device that + * names no network vendor but mentions Linux in either is a Linux device. * * The names match the vendor field of the bundled catalogues in docs/. * @@ -569,6 +570,14 @@ function syslog_recommendation_vendor_from_device(string $sys_descr, string $tem } } + // Many network operating systems run on Linux and report it, so Linux is the + // fallback when neither the description nor the template names a vendor. + foreach ([$sys_descr, $template] as $text) { + if (preg_match('/\blinux\b/i', $text)) { + return 'Linux'; + } + } + return ''; } diff --git a/tests/Unit/RecommendationsTest.php b/tests/Unit/RecommendationsTest.php index 912b6522..560117be 100644 --- a/tests/Unit/RecommendationsTest.php +++ b/tests/Unit/RecommendationsTest.php @@ -397,7 +397,8 @@ function recommendation_sample(array $override = []): array { 'Nokia' => ['nokia.json.gz', 'Nokia', 2016], 'Fortinet' => ['fortinet.json.gz', 'Fortinet', 1462], 'Palo Alto Networks' => ['paloalto.json.gz', 'Palo Alto Networks', 364], - 'MikroTik' => ['mikrotik.json.gz', 'MikroTik', 11] + 'MikroTik' => ['mikrotik.json.gz', 'MikroTik', 11], + 'Linux' => ['linux.json.gz', 'Linux', 102] ]); it('streams compressed exports across database pages without changing the filters or records', function () { @@ -645,10 +646,13 @@ function recommendation_sample(array $override = []): array { 'template only' => ['', 'Arista Switch', 'Arista'], 'template fallback' => ['Hardware: Intel64 Family 6 - Software: Windows Version 6.3', 'Palo Alto Firewall', 'Palo Alto Networks'], 'ProCurve model' => ['HP J9772A 2530-48G-PoEP Switch, revision YA.16.10.0009', '', 'HPE'], - 'Net-SNMP host' => ['Linux cisco-syslog01 5.15.0-91-generic #101-Ubuntu SMP x86_64', '', ''], - 'HP server name' => ['Linux hp-dl380-01 6.1.0 #1 SMP x86_64', '', ''], + 'Net-SNMP host' => ['Linux cisco-syslog01 5.15.0-91-generic #101-Ubuntu SMP x86_64', '', 'Linux'], + 'HP server name' => ['Linux hp-dl380-01 6.1.0 #1 SMP x86_64', '', 'Linux'], + 'Linux template' => ['', 'Linux Local Machine', 'Linux'], + 'vendor template over Linux' => ['Linux leaf01 4.19.0 #1 SMP x86_64', 'Arista Switch', 'Arista'], + 'Nokia SR Linux' => ['SRLinux-v23.10.1 7220 IXR-D2L Copyright (c) 2023 Nokia', '', 'Nokia'], 'Alcatel-Lucent' => ['Alcatel-Lucent Enterprise OS6860E-48 8.7.354.R01 GA', '', ''], - 'unknown' => ['Linux web01 6.1.0 x86_64', 'Generic SNMP Device', ''] + 'unknown' => ['Hardware: Intel64 Family 6 - Software: Windows Version 6.3', 'Generic SNMP Device', ''] ]); it('scopes recommendations to the vendor of the sending Cacti device', function () { @@ -717,6 +721,48 @@ function recommendation_sample(array $override = []): array { expect(array_column(syslog_recommendations_lookup('Port 4701 changed state', 3, 'vendor-scope-hpe'), 'vendor'))->toBe(['HPE']); }); +it('matches a forwarded systemd MESSAGE_ID from a Linux host against the Linux catalogue', function () { + $records = syslog_recommendations_parse(syslog_recommendations_read_file(dirname(__DIR__, 2) . '/docs/linux.json.gz'))['records']; + $db = new PDO('sqlite::memory:'); + $db->exec('CREATE TABLE syslog_recommendations (identifier TEXT, vendor TEXT, component TEXT, + severity INTEGER, message TEXT, explanation TEXT, recommended_action TEXT, reference TEXT)'); + $insert = $db->prepare('INSERT INTO syslog_recommendations VALUES (?, ?, ?, ?, ?, ?, ?, ?)'); + + foreach ($records as $record) { + $insert->execute([$record['identifier'], $record['vendor'], $record['component'], $record['severity'], + $record['message'], $record['explanation'], $record['recommended_action'], $record['reference']]); + } + $insert->execute(['%LINK-3-UPDOWN', 'Cisco', '', null, '', 'A link changed state.', '', '']); + + test_override('syslog_db_fetch_assoc_prepared', function ($sql, $params) use ($db) { + $statement = $db->prepare(str_replace('CHAR_LENGTH(', 'LENGTH(', $sql)); + $statement->execute($params); + + return $statement->fetchAll(PDO::FETCH_ASSOC); + }); + test_override('syslog_db_fetch_cell_prepared', function ($sql, $params) use ($db) { + $statement = $db->prepare($sql); + $statement->execute($params); + + return $statement->fetchColumn(); + }); + test_override('db_fetch_assoc_prepared', function ($sql, $params) { + return str_contains($sql, 'WHERE h.description') && in_array('linux-catalogue-web01', $params, true) + ? [['id' => 1, 'name' => 'linux-catalogue-web01', 'snmp_sysDescr' => 'Linux web01 6.1.0 #1 SMP x86_64', 'template' => '']] + : []; + }); + + // The forwarder template appends the journal field as MESSAGE_ID=. + $failed = 'Failed to start nginx.service - A high performance web server. MESSAGE_ID=be02cf6855d2428ba40df7e9d022f03d'; + $match = syslog_recommendations_lookup($failed, 3, 'linux-catalogue-web01'); + + expect(array_column($match, 'identifier'))->toBe(['be02cf6855d2428ba40df7e9d022f03d']) + ->and($match[0]['vendor'])->toBe('Linux') + ->and($match[0]['message'])->toBe('A start job for unit @UNIT@ has failed') + ->and(syslog_recommendations_lookup($failed, 3, 'linux-catalogue-unknown'))->toHaveCount(1) + ->and(syslog_recommendations_lookup('%LINK-3-UPDOWN: Interface eth0 down', 3, 'linux-catalogue-web01'))->toBe([]); +}); + it('resolves host vendors across case, numeric names and ambiguous device matches', function () { // Rows as a case-insensitive Cacti database returns them for the requested names. test_override('db_fetch_assoc_prepared', function ($sql, $params) { @@ -732,7 +778,7 @@ function recommendation_sample(array $override = []): array { ['id' => 14, 'name' => 'SHARED-NAME', 'snmp_sysDescr' => 'HPE Comware Platform Software', 'template' => ''], ['id' => 15, 'name' => 'same-vendor', 'snmp_sysDescr' => 'Juniper Networks JUNOS', 'template' => ''], ['id' => 16, 'name' => 'same-vendor', 'snmp_sysDescr' => 'Juniper Networks JUNOS', 'template' => ''], - ['id' => 18, 'name' => 'partly-known', 'snmp_sysDescr' => 'Linux server', 'template' => ''] + ['id' => 18, 'name' => 'partly-known', 'snmp_sysDescr' => 'Generic SNMP agent', 'template' => ''] ]; return array_values(array_filter($rows, static fn ($row) => in_array(strtolower($row['name']), array_map('strtolower', $params), true)));