Update report special keyword

This commit is contained in:
nguyentrungthat 2026-01-29 08:43:26 +07:00
parent d0022eb7d5
commit 7373601fa4
4 changed files with 80 additions and 27 deletions

View File

@ -438,7 +438,7 @@ export default class LineConnection {
}) })
this.outputBuffer = '' this.outputBuffer = ''
this.outputScenario = '' this.outputScenario = ''
this.config.output += 'Timeout run scenario' this.config.output += '\nTimeout run scenario\n'
this.dataDPELP = { this.dataDPELP = {
line: this.config.lineNumber, line: this.config.lineNumber,
pid: '', pid: '',
@ -453,7 +453,7 @@ export default class LineConnection {
this.socketIO.emit('line_output', { this.socketIO.emit('line_output', {
stationId: this.config.stationId, stationId: this.config.stationId,
lineId: this.config.id, lineId: this.config.id,
data: 'Timeout run scenario', data: '\nTimeout run scenario\n',
}) })
this.outputScenario += `\n---end-scenarios---${now}---${userName}---\n` this.outputScenario += `\n---end-scenarios---${now}---${userName}---\n`
appendLog( appendLog(
@ -970,7 +970,7 @@ export default class LineConnection {
// console.log(detectLog) // console.log(detectLog)
const tableHTML = this.buildEmailContent(result) const tableHTML = this.buildEmailContent(result)
await sendMessageToMail( await sendMessageToMail(
`[ATC] - [${this.config.stationName} - Line: ${this.config.lineNumber}] - Raw log issue`, `[ATC] - [${this.config.stationName} - Line: ${this.config.lineNumber}] - Raw log issue ${result?.errors?.some((e) => e.category === 'SPECIAL_KEYWORD') ? '+ Special keywords' : ''}`,
tableHTML + tableHTML +
`${` `${`
<hr /> <hr />
@ -1012,7 +1012,7 @@ export default class LineConnection {
</td> </td>
<td style="padding:6px; text-align:center;">${r.rule}</td> <td style="padding:6px; text-align:center;">${r.rule}</td>
<td style="padding:6px; text-align:center;">${r.message}</td> <td style="padding:6px; text-align:center;">${r.message}</td>
<td style="padding:6px; font-family:monospace;">*${escapeHtml(r.log.trim()) <td style="padding:6px; font-family:monospace;">${escapeHtml(r.log.trim())
.split('*') .split('*')
.filter((el) => el) .filter((el) => el)
.join('<br/>*')}</td> .join('<br/>*')}</td>

View File

@ -8,6 +8,7 @@ import axios from 'axios'
import moment from 'moment' import moment from 'moment'
import Station from '#models/station' import Station from '#models/station'
import ConfigRam from '#models/config_ram' import ConfigRam from '#models/config_ram'
import Keyword from '#models/keywords'
const mailTo = 'andrew.ng@apactech.io' const mailTo = 'andrew.ng@apactech.io'
const mailCC = [ const mailCC = [
@ -36,7 +37,10 @@ type InputData = {
// Types // Types
type SendMailResponse = string type SendMailResponse = string
type SendMessageType = 'stream' | 'private' type SendMessageType = 'stream' | 'private'
type KeywordMatchType = 'contains' | 'exact'
interface KeywordRule extends LogRule {
keywordId?: number
}
/** /**
* Function to clean up unwanted characters from the output data. * Function to clean up unwanted characters from the output data.
* @param {string} data - The raw data to be cleaned. * @param {string} data - The raw data to be cleaned.
@ -393,7 +397,7 @@ export function classifyLog(line: string): ParsedLog {
if (/ERROR|FAIL|CRITICAL|Traceback/.test(line)) return { raw: line, category: 'ERROR' } if (/ERROR|FAIL|CRITICAL|Traceback/.test(line)) return { raw: line, category: 'ERROR' }
return { raw: line, category: 'UNKNOWN' } return { raw: line, category: 'SPECIAL_KEYWORD' }
} }
export const RULES: LogRule[] = [ export const RULES: LogRule[] = [
@ -537,32 +541,36 @@ export const RULES: LogRule[] = [
}, },
] ]
export function applyRules(log: ParsedLog): TestError[] { export async function applyRules(log: ParsedLog): Promise<TestError[]> {
return RULES.filter( const KEYWORD_RULES: KeywordRule[] = await loadKeywordRules(log.raw)
(rule): rule is LogRule & { level: 'FAIL' | 'WARN' } => return [...RULES, ...KEYWORD_RULES]
rule.category === log.category && rule.match.test(log.raw) && rule.level !== 'PASS' .filter(
).map((rule) => ({ (rule): rule is LogRule & { level: 'FAIL' | 'WARN' } =>
ruleId: rule.id, rule.category === log.category && rule.match.test(log.raw) && rule.level !== 'PASS'
level: rule.level, // ✅ giờ TS biết chắc chỉ FAIL | WARN )
message: rule.message, .map((rule) => ({
evidence: { ruleId: rule.id,
raw: log.raw, level: rule.level, // ✅ giờ TS biết chắc chỉ FAIL | WARN
timestamp: log.timestamp, message: rule.message,
}, category: rule.category,
})) evidence: {
raw: log.raw,
timestamp: log.timestamp,
},
}))
} }
export class TestSession { export class TestSession {
bootOk = false bootOk = false
errors: TestError[] = [] errors: TestError[] = []
applyParsedLog(log: ParsedLog) { async applyParsedLog(log: ParsedLog) {
// Detect boot OK // Detect boot OK
if (/IOS XE Software|System Bootstrap/.test(log.raw)) { if (/IOS XE Software|System Bootstrap/.test(log.raw)) {
this.bootOk = true this.bootOk = true
} }
const matchedErrors = applyRules(log) const matchedErrors = await applyRules(log)
matchedErrors.forEach((err) => this.addError(err)) matchedErrors.forEach((err) => this.addError(err))
} }
@ -595,7 +603,7 @@ export class TestSession {
const hasWarn = this.errors.some((e) => e.level === 'WARN') const hasWarn = this.errors.some((e) => e.level === 'WARN')
let status: TestResult['status'] = 'PASS' let status: TestResult['status'] = 'PASS'
if (!this.bootOk || hasFail) status = 'FAIL' if (hasFail) status = 'FAIL'
else if (hasWarn) status = 'PARTIAL' else if (hasWarn) status = 'PARTIAL'
return { return {
@ -1476,3 +1484,40 @@ export function convertToKilobytes(input: string): number {
return Math.round(value * unitMultipliers[unit]) return Math.round(value * unitMultipliers[unit])
} }
function escapeRegex(str: string) {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}
function keywordToRule(keyword: Keyword): KeywordRule {
let match: RegExp
switch (keyword.match_type) {
case 'exact':
match = new RegExp(`^${escapeRegex(keyword.name)}$`, 'i')
break
case 'contains':
default:
match = new RegExp(escapeRegex(keyword.name), 'i')
}
return {
id: `${keyword.name}`,
keywordId: keyword.id,
category: 'SPECIAL_KEYWORD',
match,
level: 'WARN',
message: `Keyword detected: ${keyword.name}`,
}
}
async function loadKeywordRules(log: string): Promise<KeywordRule[]> {
const keywords = await Keyword.query()
for (const keyword of keywords) {
if (log.toUpperCase().includes(keyword.name.toUpperCase())) {
return keywords.map(keywordToRule)
}
}
return []
}

View File

@ -8,7 +8,14 @@ export interface CustomServer extends Server {
userKeys?: string[] userKeys?: string[]
} }
type LogCategory = 'BOOT' | 'LICENSE' | 'INTERFACE' | 'HARDWARE' | 'ERROR' | 'UNKNOWN' type LogCategory =
| 'BOOT'
| 'LICENSE'
| 'INTERFACE'
| 'HARDWARE'
| 'ERROR'
| 'UNKNOWN'
| 'SPECIAL_KEYWORD'
export interface ParsedLog { export interface ParsedLog {
raw: string raw: string
@ -35,6 +42,7 @@ export interface TestError {
ruleId: string ruleId: string
level: 'FAIL' | 'WARN' level: 'FAIL' | 'WARN'
message: string message: string
category: string
evidence: { evidence: {
raw: string raw: string
timestamp?: Date timestamp?: Date

View File

@ -24,7 +24,7 @@ const LIST_TYPE = [
]; ];
const LIST_MATCH_TYPE = [ const LIST_MATCH_TYPE = [
{ value: "exact", label: "Exact" }, { value: "exact", label: "Exact" },
{ value: "include", label: "Include" }, { value: "contains", label: "Contains" },
]; ];
interface Props { interface Props {
opened: boolean; opened: boolean;
@ -37,7 +37,7 @@ export default function ModalKeywords({ opened, onClose }: Props) {
const [newKeywords, setNewKeywords] = useState<Keywords>({ const [newKeywords, setNewKeywords] = useState<Keywords>({
name: "", name: "",
type: "special_model", type: "special_model",
match_type: "include", match_type: "contains",
is_active: true, is_active: true,
}); });
const [inputModel, setInputModel] = useState<string>(""); const [inputModel, setInputModel] = useState<string>("");
@ -64,7 +64,7 @@ export default function ModalKeywords({ opened, onClose }: Props) {
setNewKeywords({ setNewKeywords({
name: "", name: "",
type: "special_model", type: "special_model",
match_type: "include", match_type: "contains",
is_active: true, is_active: true,
}); });
} }
@ -104,7 +104,7 @@ export default function ModalKeywords({ opened, onClose }: Props) {
setNewKeywords({ setNewKeywords({
name: "", name: "",
type: "special_model", type: "special_model",
match_type: "include", match_type: "contains",
is_active: true, is_active: true,
}); });
setDisabled(false); setDisabled(false);