-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStatusLineModels.cs
More file actions
195 lines (168 loc) · 8.6 KB
/
Copy pathStatusLineModels.cs
File metadata and controls
195 lines (168 loc) · 8.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json;
namespace WebToolsDataMonitor
{
// --- Core Unified Display Row Model ---
public class StatusLineItem
{
public string Tool { get; set; }
public string PageUrl { get; set; } // Which tools/pages/*.yaml destinationUrl produced this row
public string ScriptName { get; set; } // Which tools/scripts/*.yaml script produced this row
public string DeviceName { get; set; }
public string MetricOrIssueName { get; set; } // e.g., "Battery capacity" or "Active Incident"
public string Value { get; set; } // e.g., "91 %" or the raw issue text string
public string ConditionSource { get; set; } // e.g., "disaster-bg", "warning-bg", "MetaNormal"
public bool IsProblemType { get; set; }
public string RowHash { get; set; } // Identity of the (Tool, PageUrl, ScriptName) batch this row belongs to - see RowHasher
public string ProblemId { get; set; } // ActiveProblems only (Zabbix event id) - null for DeviceMeta rows. See Form2.GetAlertKey.
public string CustomRuleDescription { get; set; } // e.g. "230 is below 250" - only set when ConditionSource came from a saved custom rule (FormulaPersistenceManager), not a fallback rule. Spoken alongside the metric name in Form2.TriggerAlert.
}
// Computes a stable identity id for a set of fields, replacing "combine several strings and compare them
// all each time" (e.g. Form2.ReplaceScriptResults used to do a 3-field && comparison) with a single
// precomputed hash comparison. Not for security use - just a compact, collision-resistant grouping key.
public static class RowHasher
{
public static string ComputeHash(params string[] parts)
{
// Unit Separator (0x1F) between parts so e.g. ("ab","c") and ("a","bc") can't collide by
// naive concatenation.
string combined = string.Join("", Array.ConvertAll(parts, p => p ?? string.Empty));
using (var sha256 = SHA256.Create())
{
byte[] hashBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(combined));
var sb = new StringBuilder(16);
for (int i = 0; i < 8; i++) // first 8 bytes (64 bits) is plenty for this grouping-key use case
sb.Append(hashBytes[i].ToString("x2"));
return sb.ToString();
}
}
}
// --- ExtractDeviceMeta JSON Deserialization Structs ---
public class DeviceMetaPayload
{
[JsonProperty("deviceName")]
public string DeviceName { get; set; }
[JsonProperty("deviceData")]
public List<DeviceMetric> DeviceData { get; set; }
}
public class DeviceMetric
{
public string Name { get; set; }
public string Value { get; set; }
}
// --- ExtractActiveProblems JSON Deserialization Struct ---
public class ActiveProblemPayload
{
public string Id { get; set; } // Zabbix event id (row's data-eventid attribute) - distinguishes multiple simultaneous problems on the same device
public string Name { get; set; }
public string Issue { get; set; }
public string Priority { get; set; }
public string Time { get; set; }
}
// --- Data Transfer Object (DTO) Transformers ---
public static class StatusLineDto
{
// DTO: Transform Active Problem Arrays into Unified Status Lines
public static List<StatusLineItem> FromActiveProblems(string tool, string pageUrl, string scriptName, string json)
{
var results = new List<StatusLineItem>();
if (string.IsNullOrEmpty(json) || json == "null") return results;
try
{
var rawProblems = JsonConvert.DeserializeObject<List<ActiveProblemPayload>>(json);
if (rawProblems == null) return results;
string rowHash = RowHasher.ComputeHash(tool, pageUrl, scriptName);
foreach (var prob in rawProblems)
{
results.Add(new StatusLineItem
{
Tool = tool,
PageUrl = pageUrl,
ScriptName = scriptName,
RowHash = rowHash,
ProblemId = prob.Id,
DeviceName = prob.Name,
MetricOrIssueName = "Active Incident",
Value = prob.Issue,
ConditionSource = prob.Priority, // e.g., "warning-bg", "average-bg", etc.
IsProblemType = true
});
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Error mapping active problems DTO data stream: {ex.Message}");
}
return results;
}
// DTO: Transform Device Metadata Objects into Unified Status Lines
public static List<StatusLineItem> FromDeviceMeta(string tool, string pageUrl, string scriptName, string json)
{
var results = new List<StatusLineItem>();
if (string.IsNullOrEmpty(json) || json == "null") return results;
try
{
var payload = JsonConvert.DeserializeObject<DeviceMetaPayload>(json);
if (payload == null || payload.DeviceData == null) return results;
string rowHash = RowHasher.ComputeHash(tool, pageUrl, scriptName);
foreach (var metric in payload.DeviceData)
{
// Evaluate status condition via custom user formula engine or system fallback
string condition = DetermineMetaConditionFormula(tool, payload.DeviceName, metric.Name, metric.Value, out string customRuleDescription);
results.Add(new StatusLineItem
{
Tool = tool,
PageUrl = pageUrl,
ScriptName = scriptName,
RowHash = rowHash,
DeviceName = payload.DeviceName,
MetricOrIssueName = metric.Name,
Value = metric.Value,
ConditionSource = condition,
CustomRuleDescription = customRuleDescription,
IsProblemType = false
});
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Error mapping device metadata DTO data stream: {ex.Message}");
}
return results;
}
// Formula rule mapper evaluating runtime metrics against user thresholds or system defaults
private static string DetermineMetaConditionFormula(string tool, string deviceName, string metricName, string value, out string customRuleDescription)
{
// 1. Check user-defined overrides via dynamic JSON persistence rules first
string userStatus = FormulaPersistenceManager.EvaluateMetric(tool, deviceName, metricName, value, out customRuleDescription);
if (userStatus != null) return userStatus;
// Fallback rules below don't have a saved rule to describe
customRuleDescription = null;
// 2. Fallback: Core Hardcoded Global Defaults Rule Matrix
if (string.IsNullOrEmpty(value)) return "MetaNormal";
// Fallback rule for ICMP Ping outages
if (metricName.Contains("ping") && value.Contains("Down")) return "MetaDisaster";
// Fallback rule for Battery Capacity scaling drops
if (metricName.Contains("capacity"))
{
string digits = System.Text.RegularExpressions.Regex.Match(value, @"\d+").Value;
if (int.TryParse(digits, out int capacityPercent))
{
if (capacityPercent < 20) return "MetaDisaster";
if (capacityPercent < 50) return "MetaAverage";
if (capacityPercent < 85) return "MetaWarning";
}
}
// Fallback rules targeting specific hardware notification keyword flags
if (value.Contains("Replace") || value.Contains("Fail") || value.Contains("Loss"))
{
if (value.Contains("0 %") || value.Contains("no Battery")) return "MetaNormal";
return "MetaWarning";
}
return "MetaNormal"; // Safe baseline visual state
}
}
}