Files
tinker_tickets/helpers/TicketHash.php
jaredandClaude Opus 5.5 7061c40d4d
Lint / JS (eslint) (push) Successful in 14s
Lint / PHP (phpcs PSR-12) (push) Successful in 44s
Lint / PHP requirements (version + extensions) (push) Successful in 42s
Lint / Deploy (push) Skipped
Lint / Notify on failure (push) Skipped
Lint / PHP (phpcs PSR-12) (pull_request) Successful in 1m15s
Lint / JS (eslint) (pull_request) Successful in 34s
Lint / PHP requirements (version + extensions) (pull_request) Successful in 42s
Lint / Deploy (pull_request) Skipped
Lint / Notify on failure (pull_request) Skipped
Security / PHP Security (semgrep) (push) Successful in 4m13s
Security / PHP Security (semgrep) (pull_request) Successful in 3m25s
Ticket contract for automated reporters: dedup_key, source, links, reopen window (#123)
From the thor#1 plan: each reporter (gandalf, hwmonDaemon, thor) decides
what "the same problem" is, and Tinker enforces it.

- dedup_key on create_ticket_api.php (scope:subject:kind, A-Za-z0-9_.:-,
  case-sensitive). The hash becomes sha256("key:" + key) and the title is
  not looked at; an invalid key is a 400. Keyless callers hash exactly as
  before (checked over every prod title).
- Recurrence window for every reporter, keyed or not: a match on a ticket
  closed under AUTO_REOPEN_WINDOW_DAYS (7) ago reopens it as before
  (subject to the Workflow Designer); an older one gets a new ticket that
  takes over the dedup slot (tickets.hash stays UNIQUE, the old ticket
  gives it up), carries the key, records recurrence_of, is linked
  relates_to, and gets a history comment. action: new_recurrence.
- GET api/tickets_api.php?dedup_key= returns the newest ticket with that
  key plus its recurrence chain; ?source= filters the list.
- New api/ticket_link_api.php (link/unlink, read_write) through
  DependencyService::link()/unlink(), now shared with MCP
  link_tickets/unlink_tickets; audit rows record the key name.
- tickets.source records the API key name. Shown as the creator instead of
  "System" on the dashboard and ticket page, a Source filter in the
  sidebar, source in MCP results and a search_tickets filter. Comments the
  create API writes name the reporter instead of a hard-coded
  "hwmonDaemon", and system-linked comments display that name.
- Migration 008 (dedup_key, source, recurrence_of). Scripts:
  backfill_ticket_source.php (pre-#123 tickets, where certain) and
  backfill_dedup_keys.php (mapping file supplied by the app).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 20:22:06 -05:00

221 lines
10 KiB
PHP

<?php
/**
* Dedup hash for tickets created through create_ticket_api.php.
*
* Two reports with the same hash land on the same ticket (updated while open,
* reopened or followed by a linked new ticket when closed). A reporter can
* send an explicit dedup_key and decide that itself (#123); otherwise the
* components below decide what counts as "the same problem". Changing them re-keys existing tickets: see
* scripts/rehash_network_tickets.php for how #116 handled that.
*/
class TicketHash
{
/**
* The stable components the hash is built from.
*
* @param array $data Request payload: title, plus optional serial / check_code.
*/
public static function components(array $data): array
{
$title = (string)($data['title'] ?? '');
// Prefer explicit serial from payload; fall back to extracting device path from title
// for backwards compatibility with older hwmonDaemon versions.
$serial = isset($data['serial']) && $data['serial'] !== null && $data['serial'] !== ''
? (string)$data['serial']
: null;
// Extract device name if present (matches /dev/sdX, /dev/nvmeXnY patterns)
preg_match('/\/dev\/(sd[a-z]+|nvme\d+n\d+)/', $title, $deviceMatches);
$isDriveTicket = !empty($deviceMatches) || $serial !== null;
// Extract first bracketed tag as hostname/source
preg_match('/^\[([^\]]+)\]/', $title, $hostMatches);
$hostname = $hostMatches[1] ?? '';
// Detect issue category and optional sub-type
$issueCategory = '';
$issueSubtype = '';
$isClusterWide = false;
if (stripos($title, 'SMART issues') !== false) {
$issueCategory = 'smart';
} elseif (stripos($title, 'ZFS pool') !== false) {
$issueCategory = 'zfs';
// Extract pool name so each pool gets its own ticket
if (preg_match("/ZFS pool '([^']+)'/i", $title, $poolMatch)) {
$poolName = strtolower(preg_replace('/[^a-z0-9_]/i', '_', $poolMatch[1]));
if (stripos($title, 'state:') !== false || preg_match('/DEGRADED|FAULTED|UNAVAIL|OFFLINE/i', $title)) {
$issueSubtype = 'pool_state_' . $poolName;
} elseif (stripos($title, 'usage') !== false) {
$issueSubtype = 'pool_usage_' . $poolName;
} elseif (stripos($title, 'errors') !== false) {
$issueSubtype = 'pool_errors_' . $poolName;
} else {
$issueSubtype = 'pool_' . $poolName;
}
}
} elseif (stripos($title, 'LXC') !== false || stripos($title, 'storage usage') !== false) {
$issueCategory = 'storage';
// Include the LXC container ID so each container gets its own ticket
if (preg_match('/LXC\s+(\d+)/i', $title, $lxcMatch)) {
$issueSubtype = 'lxc_' . $lxcMatch[1];
}
} elseif (stripos($title, 'memory') !== false) {
$issueCategory = 'memory';
} elseif (stripos($title, 'cpu') !== false) {
$issueCategory = 'cpu';
} elseif (stripos($title, 'network') !== false) {
$issueCategory = 'network';
// One ticket per kind of network problem per host, not one per
// host. With an empty subtype every network alert for a host
// (reboot, NIC link-down, cable mismatch, ...) hashed alike, so an
// interface alert landed on an unrelated closed reboot ticket
// (#116). Prefer the reporter's check_code when sent; it must name
// the instance too (e.g. "iface_down:enp3s0"), not just the alert
// type. Otherwise key on the title text outside the [tags]; the
// reporters' headings are stable per problem, and digits are kept
// because they identify it (enp3s0, cable C07). Manual tickets
// are already keyed on their full title, so they are left as-is.
$checkCode = isset($data['check_code']) && is_string($data['check_code']) ? $data['check_code'] : '';
if (stripos($title, '[auto]') === false) {
// manual: unchanged hash
} elseif ($checkCode !== '' && preg_match('/^[A-Za-z0-9_.:-]{1,80}$/', $checkCode)) {
$issueSubtype = 'net_check_' . strtolower($checkCode);
} else {
$heading = trim(preg_replace('/\[[^\]]*\]/', '', $title), " -\t");
$slug = trim(preg_replace('/[^a-z0-9]+/', '_', strtolower($heading)), '_');
if ($slug !== '') {
$issueSubtype = 'net_' . substr($slug, 0, 80);
}
}
} elseif (stripos($title, 'Ceph') !== false || stripos($title, '[ceph]') !== false) {
$issueCategory = 'ceph';
if (
stripos($title, '[cluster-wide]') !== false ||
stripos($title, 'HEALTH_ERR') !== false ||
stripos($title, 'HEALTH_WARN') !== false ||
stripos($title, 'cluster usage') !== false
) {
$isClusterWide = true;
}
// Normalize the specific Ceph warning type so different warnings get distinct tickets
if (stripos($title, 'slow') !== false && stripos($title, 'BlueStore') !== false) {
$issueSubtype = 'bluestore_slow';
} elseif (stripos($title, 'clock skew') !== false) {
$issueSubtype = 'clock_skew';
} elseif (stripos($title, 'cluster usage') !== false) {
$issueSubtype = 'usage';
} elseif (stripos($title, 'OSD down') !== false || preg_match('/osd\.\d+\s+is\s+DOWN/i', $title)) {
// Include the specific OSD ID so each individual OSD gets its own ticket
if (preg_match('/osd\.(\d+)/i', $title, $osdMatch)) {
$issueSubtype = 'osd_down_' . $osdMatch[1];
} else {
$issueSubtype = 'osd_down';
}
} elseif (stripos($title, 'HEALTH_ERR') !== false) {
$issueSubtype = 'health_err';
} else {
// Any other warning gets its own ticket. Previously every other
// HEALTH_WARN shared one empty subtype, so unrelated warnings
// (noout, nearfull, insecure keys, ...) collapsed onto a single
// ticket and overwrote its title in turn every run (#112).
// Prefer Ceph's own health-check code when the reporter sends
// it; otherwise key on the warning text with counts stripped.
$checkCode = isset($data['check_code']) && is_string($data['check_code']) ? $data['check_code'] : '';
if ($checkCode !== '' && preg_match('/^[A-Z0-9_]{1,64}$/', $checkCode)) {
$issueSubtype = 'check_' . strtolower($checkCode);
} elseif (preg_match('/HEALTH_WARN:\s*([^\[]+)/i', $title, $warnMatch)) {
$warnText = strtolower(explode(':', $warnMatch[1])[0]);
$warnText = trim(preg_replace('/[^a-z]+/', '_', $warnText), '_');
if ($warnText !== '') {
$issueSubtype = 'warn_' . $warnText;
}
}
}
}
// Include source type so automated tickets never collide with manual ones
$sourceType = stripos($title, '[auto]') !== false ? 'auto' : 'manual';
// Build stable components
$stableComponents = [
'source_type' => $sourceType,
'issue_category' => $issueCategory,
'issue_subtype' => $issueSubtype,
'environment_tags' => (function () use ($title) {
// Extract each [bracketed] tag, then keep the known environment ones.
// (explode('][') leaves brackets stuck to the first/last tag, so e.g.
// "[production] ..." never matched and the env tag was dropped from the
// dedup hash — letting prod and staging issues collide onto one ticket.)
preg_match_all('/\[([^\]]+)\]/', $title, $m);
return array_values(array_filter(
$m[1],
fn($tag) => in_array($tag, ['production', 'development', 'staging', 'single-node', 'cluster-wide'], true)
));
})(),
];
// Manual tickets should be unique by title (so different software installs don't collide)
if ($sourceType === 'manual') {
$stableComponents['title'] = $title;
}
// Include hostname for node-specific issues
if (!$isClusterWide) {
$stableComponents['hostname'] = $hostname;
}
// Include drive identifier for drive-specific tickets.
// Use serial when available (stable across reboots/reshuffles); fall back to
// device path for tickets created before serial was added to the payload.
if ($isDriveTicket) {
$stableComponents['drive'] = $serial ?? ($deviceMatches[0] ?? '');
}
sort($stableComponents['environment_tags']);
return $stableComponents;
}
/**
* Format of a reporter-supplied dedup_key: scope:subject:kind, e.g.
* host:compute-storage-01:oom or cluster:ceph:BLUESTORE_SLOW_OP_ALERT.
* Upper case is allowed for codes like Ceph's; keys are case-sensitive.
*/
public const KEY_PATTERN = '/^[A-Za-z0-9_.:-]{1,128}$/';
public static function isValidKey($key): bool
{
return is_string($key) && preg_match(self::KEY_PATTERN, $key) === 1;
}
/** The request's dedup_key, or null when it sent none. Validate with isValidKey() first. */
public static function key(array $data): ?string
{
$key = $data['dedup_key'] ?? null;
return ($key === null || $key === '') ? null : (string)$key;
}
/** Dedup hash for an explicit key. The "key:" prefix keeps it apart from every legacy hash. */
public static function forKey(string $key): string
{
return hash('sha256', 'key:' . $key);
}
/**
* Dedup hash for a create request. With a dedup_key the reporter decides
* what "the same problem" is and the title is not looked at (#123);
* without one, the stable components of the title decide, as before.
*/
public static function generate(array $data): string
{
$key = self::key($data);
if ($key !== null) {
return self::forKey($key);
}
return hash('sha256', json_encode(self::components($data), JSON_UNESCAPED_SLASHES));
}
}