iobroker.unraid 0.5.0 → 0.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +47 -6
- package/admin/build/index.js +8 -8
- package/admin/build/index.js.map +3 -3
- package/build/apollo-client.d.ts +60 -7
- package/build/apollo-client.d.ts.map +1 -1
- package/build/apollo-client.js +69 -24
- package/build/apollo-client.js.map +1 -1
- package/build/config/adapter-config.d.ts +30 -0
- package/build/config/adapter-config.d.ts.map +1 -0
- package/build/config/adapter-config.js +50 -0
- package/build/config/adapter-config.js.map +1 -0
- package/build/graphql/selection-builder.d.ts +43 -0
- package/build/graphql/selection-builder.d.ts.map +1 -0
- package/build/graphql/selection-builder.js +108 -0
- package/build/graphql/selection-builder.js.map +1 -0
- package/build/main.js +88 -842
- package/build/main.js.map +1 -1
- package/build/managers/dynamic-resource-manager.d.ts +73 -0
- package/build/managers/dynamic-resource-manager.d.ts.map +1 -0
- package/build/managers/dynamic-resource-manager.js +445 -0
- package/build/managers/dynamic-resource-manager.js.map +1 -0
- package/build/managers/polling-manager.d.ts +64 -0
- package/build/managers/polling-manager.d.ts.map +1 -0
- package/build/managers/polling-manager.js +143 -0
- package/build/managers/polling-manager.js.map +1 -0
- package/build/managers/state-manager.d.ts +64 -0
- package/build/managers/state-manager.d.ts.map +1 -0
- package/build/managers/state-manager.js +182 -0
- package/build/managers/state-manager.js.map +1 -0
- package/build/shared/unraid-domains.d.ts +83 -0
- package/build/shared/unraid-domains.d.ts.map +1 -1
- package/build/shared/unraid-domains.js +88 -18
- package/build/shared/unraid-domains.js.map +1 -1
- package/build/subscription-manager.js +94 -43
- package/build/subscription-manager.js.map +1 -1
- package/build/types/adapter-types.d.ts +10 -0
- package/build/types/adapter-types.d.ts.map +1 -0
- package/build/types/adapter-types.js +7 -0
- package/build/types/adapter-types.js.map +1 -0
- package/build/utils/data-transformers.d.ts +55 -0
- package/build/utils/data-transformers.d.ts.map +1 -0
- package/build/utils/data-transformers.js +137 -0
- package/build/utils/data-transformers.js.map +1 -0
- package/io-package.json +34 -2
- package/package.json +4 -10
- package/build/subscription-manager.d.ts +0 -78
- package/build/subscription-manager.d.ts.map +0 -1
package/build/main.js
CHANGED
|
@@ -2,111 +2,29 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
const adapter_core_1 = require("@iobroker/adapter-core");
|
|
4
4
|
const apollo_client_1 = require("./apollo-client");
|
|
5
|
-
const
|
|
5
|
+
const state_manager_1 = require("./managers/state-manager");
|
|
6
|
+
const dynamic_resource_manager_1 = require("./managers/dynamic-resource-manager");
|
|
7
|
+
const polling_manager_1 = require("./managers/polling-manager");
|
|
8
|
+
const adapter_config_1 = require("./config/adapter-config");
|
|
6
9
|
const unraid_domains_1 = require("./shared/unraid-domains");
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
if (!selection.fields.length) {
|
|
12
|
-
continue;
|
|
13
|
-
}
|
|
14
|
-
const rootNode = this.getOrCreateRoot(selection.root);
|
|
15
|
-
this.addFields(rootNode, selection.fields);
|
|
16
|
-
}
|
|
17
|
-
}
|
|
18
|
-
build() {
|
|
19
|
-
if (!this.roots.size) {
|
|
20
|
-
return null;
|
|
21
|
-
}
|
|
22
|
-
const sections = [];
|
|
23
|
-
const sortedRoots = Array.from(this.roots.keys()).sort((left, right) => left.localeCompare(right));
|
|
24
|
-
for (const root of sortedRoots) {
|
|
25
|
-
const node = this.roots.get(root);
|
|
26
|
-
if (!node) {
|
|
27
|
-
continue;
|
|
28
|
-
}
|
|
29
|
-
const body = this.printNode(node, 8);
|
|
30
|
-
const section = body
|
|
31
|
-
? ` ${root} {\n${body}\n }`
|
|
32
|
-
: ` ${root}`;
|
|
33
|
-
sections.push(section);
|
|
34
|
-
}
|
|
35
|
-
const queryBody = sections.join('\n');
|
|
36
|
-
return `query UnraidAdapterFetch {\n${queryBody}\n}`;
|
|
37
|
-
}
|
|
38
|
-
getOrCreateRoot(root) {
|
|
39
|
-
const existing = this.roots.get(root);
|
|
40
|
-
if (existing) {
|
|
41
|
-
return existing;
|
|
42
|
-
}
|
|
43
|
-
const node = new Map();
|
|
44
|
-
this.roots.set(root, node);
|
|
45
|
-
return node;
|
|
46
|
-
}
|
|
47
|
-
addFields(target, fields) {
|
|
48
|
-
for (const field of fields) {
|
|
49
|
-
let child = target.get(field.name);
|
|
50
|
-
if (!child) {
|
|
51
|
-
child = new Map();
|
|
52
|
-
target.set(field.name, child);
|
|
53
|
-
}
|
|
54
|
-
if (field.selection?.length) {
|
|
55
|
-
this.addFields(child, field.selection);
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
printNode(node, indent) {
|
|
60
|
-
if (!node.size) {
|
|
61
|
-
return '';
|
|
62
|
-
}
|
|
63
|
-
const indentString = ' '.repeat(indent);
|
|
64
|
-
const entries = Array.from(node.entries()).sort((left, right) => left[0].localeCompare(right[0]));
|
|
65
|
-
return entries
|
|
66
|
-
.map(([name, child]) => {
|
|
67
|
-
if (!child.size) {
|
|
68
|
-
return `${indentString}${name}`;
|
|
69
|
-
}
|
|
70
|
-
const body = this.printNode(child, indent + 4);
|
|
71
|
-
if (!body) {
|
|
72
|
-
return `${indentString}${name}`;
|
|
73
|
-
}
|
|
74
|
-
return `${indentString}${name} {\n${body}\n${indentString}}`;
|
|
75
|
-
})
|
|
76
|
-
.join('\n');
|
|
77
|
-
}
|
|
78
|
-
}
|
|
10
|
+
/**
|
|
11
|
+
* Main adapter class for connecting ioBroker to Unraid servers.
|
|
12
|
+
* Manages GraphQL polling, WebSocket subscriptions, and state updates.
|
|
13
|
+
*/
|
|
79
14
|
class UnraidAdapter extends adapter_core_1.Adapter {
|
|
80
|
-
pollIntervalMs = 60000;
|
|
81
|
-
pollTimer;
|
|
82
|
-
stopRequested = false;
|
|
83
15
|
apolloClient;
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
16
|
+
stateManager;
|
|
17
|
+
dynamicResourceManager;
|
|
18
|
+
pollingManager;
|
|
19
|
+
unraidConfig;
|
|
88
20
|
effectiveSelection = new Set();
|
|
89
21
|
selectedDefinitions = [];
|
|
90
22
|
staticObjectIds = new Set();
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
// Dynamic array disk tracking
|
|
97
|
-
arrayDisksDetected = false;
|
|
98
|
-
diskCount = 0;
|
|
99
|
-
parityCount = 0;
|
|
100
|
-
cacheCount = 0;
|
|
101
|
-
// Dynamic docker container tracking
|
|
102
|
-
dockerContainersDetected = false;
|
|
103
|
-
containerNames = new Set();
|
|
104
|
-
// Dynamic shares tracking
|
|
105
|
-
sharesDetected = false;
|
|
106
|
-
shareNames = new Set();
|
|
107
|
-
// Dynamic VM tracking
|
|
108
|
-
vmsDetected = false;
|
|
109
|
-
vmUuids = new Set();
|
|
23
|
+
/**
|
|
24
|
+
* Creates a new Unraid adapter instance
|
|
25
|
+
*
|
|
26
|
+
* @param options - Adapter options from ioBroker
|
|
27
|
+
*/
|
|
110
28
|
constructor(options = {}) {
|
|
111
29
|
super({
|
|
112
30
|
...options,
|
|
@@ -116,43 +34,59 @@ class UnraidAdapter extends adapter_core_1.Adapter {
|
|
|
116
34
|
this.on('unload', this.onUnload.bind(this));
|
|
117
35
|
this.on('stateChange', this.onStateChange.bind(this));
|
|
118
36
|
}
|
|
37
|
+
/**
|
|
38
|
+
* Called when the adapter is ready to start.
|
|
39
|
+
* Initializes connections and starts polling.
|
|
40
|
+
*/
|
|
119
41
|
async onReady() {
|
|
120
42
|
try {
|
|
121
|
-
|
|
122
|
-
|
|
43
|
+
// Validate configuration
|
|
44
|
+
const config = (0, adapter_config_1.validateConfig)(this.config, this.log);
|
|
45
|
+
if (!config) {
|
|
123
46
|
this.log.warn('Adapter is idle because the configuration is incomplete.');
|
|
124
47
|
return;
|
|
125
48
|
}
|
|
126
|
-
this.
|
|
49
|
+
this.unraidConfig = config;
|
|
50
|
+
// Configure domain selection
|
|
51
|
+
this.configureSelection(config.enabledDomains);
|
|
127
52
|
if (!this.selectedDefinitions.length) {
|
|
128
53
|
this.log.warn('No domains selected. Configure at least one domain in the adapter settings.');
|
|
129
54
|
return;
|
|
130
55
|
}
|
|
131
|
-
//
|
|
56
|
+
// Initialize managers
|
|
57
|
+
this.stateManager = new state_manager_1.StateManager(this);
|
|
58
|
+
this.dynamicResourceManager = new dynamic_resource_manager_1.DynamicResourceManager(this, this.stateManager);
|
|
59
|
+
// Initialize Apollo Client
|
|
132
60
|
this.apolloClient = new apollo_client_1.UnraidApolloClient({
|
|
133
|
-
baseUrl:
|
|
134
|
-
apiToken:
|
|
135
|
-
allowSelfSigned:
|
|
61
|
+
baseUrl: config.baseUrl,
|
|
62
|
+
apiToken: config.apiToken,
|
|
63
|
+
allowSelfSigned: config.allowSelfSigned,
|
|
136
64
|
});
|
|
137
|
-
|
|
138
|
-
this.
|
|
139
|
-
|
|
140
|
-
await this.
|
|
65
|
+
// Initialize polling manager
|
|
66
|
+
this.pollingManager = new polling_manager_1.PollingManager(this, this.apolloClient, this.handlePolledData.bind(this));
|
|
67
|
+
// Clean up and initialize states
|
|
68
|
+
await this.stateManager.cleanupObjectTree(this.staticObjectIds);
|
|
69
|
+
await this.stateManager.initializeStaticStates(this.selectedDefinitions);
|
|
141
70
|
// Subscription support disabled for now (API issues)
|
|
142
|
-
// if (
|
|
71
|
+
// if (config.useSubscriptions) {
|
|
143
72
|
// await this.initializeSubscriptions();
|
|
144
73
|
// }
|
|
145
74
|
// Start polling
|
|
146
|
-
|
|
147
|
-
this.scheduleNextPoll();
|
|
75
|
+
this.pollingManager.start(config.pollIntervalSeconds * 1000, this.selectedDefinitions);
|
|
148
76
|
}
|
|
149
77
|
catch (error) {
|
|
150
78
|
this.log.error(`Failed to initialise adapter: ${this.describeError(error)}`);
|
|
151
79
|
}
|
|
152
80
|
}
|
|
81
|
+
/**
|
|
82
|
+
* Configure which domains should be queried based on settings.
|
|
83
|
+
* Expands the selection to include dependencies.
|
|
84
|
+
*
|
|
85
|
+
* @param enabledDomains - List of explicitly enabled domain IDs
|
|
86
|
+
*/
|
|
153
87
|
configureSelection(enabledDomains) {
|
|
154
|
-
|
|
155
|
-
this.effectiveSelection = (0, unraid_domains_1.expandSelection)(
|
|
88
|
+
const rawSelection = new Set(enabledDomains);
|
|
89
|
+
this.effectiveSelection = (0, unraid_domains_1.expandSelection)(rawSelection);
|
|
156
90
|
const definitions = [];
|
|
157
91
|
for (const id of this.effectiveSelection) {
|
|
158
92
|
const definition = unraid_domains_1.domainDefinitionById.get(id);
|
|
@@ -161,34 +95,22 @@ class UnraidAdapter extends adapter_core_1.Adapter {
|
|
|
161
95
|
}
|
|
162
96
|
}
|
|
163
97
|
this.selectedDefinitions = definitions;
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
if (!this.effectiveSelection.has('metrics.cpu')) {
|
|
167
|
-
this.cpuCoresDetected = false;
|
|
168
|
-
this.cpuCoreCount = 0;
|
|
169
|
-
}
|
|
170
|
-
if (!this.effectiveSelection.has('array.disks') &&
|
|
171
|
-
!this.effectiveSelection.has('array.parities') &&
|
|
172
|
-
!this.effectiveSelection.has('array.caches')) {
|
|
173
|
-
this.arrayDisksDetected = false;
|
|
174
|
-
this.diskCount = 0;
|
|
175
|
-
this.parityCount = 0;
|
|
176
|
-
this.cacheCount = 0;
|
|
177
|
-
}
|
|
178
|
-
if (!this.effectiveSelection.has('docker.containers')) {
|
|
179
|
-
this.dockerContainersDetected = false;
|
|
180
|
-
this.containerNames.clear();
|
|
181
|
-
}
|
|
182
|
-
if (!this.effectiveSelection.has('shares.list')) {
|
|
183
|
-
this.sharesDetected = false;
|
|
184
|
-
this.shareNames.clear();
|
|
98
|
+
if (this.stateManager) {
|
|
99
|
+
this.staticObjectIds = this.stateManager.collectStaticObjectIds(definitions);
|
|
185
100
|
}
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
this.
|
|
101
|
+
else {
|
|
102
|
+
// Fallback for initialization phase
|
|
103
|
+
this.staticObjectIds = this.collectStaticObjectIdsTemp(definitions);
|
|
189
104
|
}
|
|
190
|
-
|
|
191
|
-
|
|
105
|
+
// Reset dynamic tracking for deselected domains
|
|
106
|
+
this.dynamicResourceManager?.resetTracking(this.effectiveSelection);
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Temporary method for collecting static object IDs during initialization
|
|
110
|
+
*
|
|
111
|
+
* @param definitions - Array of domain definitions to collect IDs from
|
|
112
|
+
*/
|
|
113
|
+
collectStaticObjectIdsTemp(definitions) {
|
|
192
114
|
const ids = new Set();
|
|
193
115
|
const addPrefixes = (identifier) => {
|
|
194
116
|
const parts = identifier.split('.');
|
|
@@ -204,693 +126,25 @@ class UnraidAdapter extends adapter_core_1.Adapter {
|
|
|
204
126
|
}
|
|
205
127
|
return ids;
|
|
206
128
|
}
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
onStateUpdate: async (id, value) => {
|
|
216
|
-
// Convert value to proper format and write state
|
|
217
|
-
const normalizedValue = value === undefined ? null : value;
|
|
218
|
-
await this.setStateAsync(id, { val: normalizedValue, ack: true });
|
|
219
|
-
},
|
|
220
|
-
onError: (error) => {
|
|
221
|
-
this.log.warn(`Subscription error: ${error.message}`);
|
|
222
|
-
},
|
|
223
|
-
onConnectionLost: () => {
|
|
224
|
-
this.log.warn('WebSocket connection lost, falling back to polling for CPU/Memory');
|
|
225
|
-
this.subscriptionsActive = false;
|
|
226
|
-
},
|
|
227
|
-
onConnectionRestored: () => {
|
|
228
|
-
this.log.info('WebSocket connection restored, using subscriptions for CPU/Memory');
|
|
229
|
-
this.subscriptionsActive = true;
|
|
230
|
-
},
|
|
231
|
-
});
|
|
232
|
-
const success = await this.subscriptionManager.start();
|
|
233
|
-
if (success) {
|
|
234
|
-
this.subscriptionsActive = true;
|
|
235
|
-
this.log.info('Subscriptions active for CPU and Memory metrics');
|
|
236
|
-
}
|
|
237
|
-
else {
|
|
238
|
-
this.log.warn('Subscriptions not available, using polling for all metrics');
|
|
239
|
-
}
|
|
240
|
-
}
|
|
241
|
-
catch (error) {
|
|
242
|
-
this.log.error(`Failed to initialize subscriptions: ${this.describeError(error)}`);
|
|
243
|
-
this.log.info('Falling back to polling for all metrics');
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
validateSettings() {
|
|
247
|
-
const baseUrl = (this.config.baseUrl ?? '').trim();
|
|
248
|
-
const apiToken = (this.config.apiToken ?? '').trim();
|
|
249
|
-
const pollIntervalSecondsRaw = Number(this.config.pollIntervalSeconds ?? 60);
|
|
250
|
-
const pollIntervalSeconds = Number.isFinite(pollIntervalSecondsRaw) && pollIntervalSecondsRaw > 0 ? pollIntervalSecondsRaw : 60;
|
|
251
|
-
const allowSelfSigned = Boolean(this.config.allowSelfSigned);
|
|
252
|
-
const useSubscriptions = Boolean(this.config.useSubscriptions);
|
|
253
|
-
const enabledDomainsRaw = Array.isArray(this.config.enabledDomains)
|
|
254
|
-
? this.config.enabledDomains
|
|
255
|
-
: [...unraid_domains_1.defaultEnabledDomains];
|
|
256
|
-
const knownIds = new Set(unraid_domains_1.allDomainIds);
|
|
257
|
-
const enabledDomains = [];
|
|
258
|
-
for (const id of enabledDomainsRaw) {
|
|
259
|
-
if (knownIds.has(id)) {
|
|
260
|
-
enabledDomains.push(id);
|
|
261
|
-
}
|
|
262
|
-
}
|
|
263
|
-
if (!enabledDomains.length) {
|
|
264
|
-
enabledDomains.push(...unraid_domains_1.defaultEnabledDomains);
|
|
265
|
-
}
|
|
266
|
-
if (!baseUrl) {
|
|
267
|
-
this.log.error('Base URL is not configured.');
|
|
268
|
-
return null;
|
|
269
|
-
}
|
|
270
|
-
if (!apiToken) {
|
|
271
|
-
this.log.error('API token is not configured.');
|
|
272
|
-
return null;
|
|
273
|
-
}
|
|
274
|
-
return {
|
|
275
|
-
baseUrl,
|
|
276
|
-
apiToken,
|
|
277
|
-
pollIntervalSeconds,
|
|
278
|
-
allowSelfSigned,
|
|
279
|
-
enabledDomains,
|
|
280
|
-
useSubscriptions,
|
|
281
|
-
};
|
|
282
|
-
}
|
|
283
|
-
scheduleNextPoll() {
|
|
284
|
-
if (this.stopRequested) {
|
|
129
|
+
/**
|
|
130
|
+
* Handle data received from polling
|
|
131
|
+
*
|
|
132
|
+
* @param data - GraphQL query result data
|
|
133
|
+
*/
|
|
134
|
+
async handlePolledData(data) {
|
|
135
|
+
if (!this.stateManager || !this.dynamicResourceManager) {
|
|
136
|
+
this.log.error('Managers not initialized');
|
|
285
137
|
return;
|
|
286
138
|
}
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
});
|
|
295
|
-
}, this.pollIntervalMs);
|
|
296
|
-
}
|
|
297
|
-
async pollOnce() {
|
|
298
|
-
if (!this.apolloClient) {
|
|
299
|
-
throw new Error('Apollo client is not initialised');
|
|
300
|
-
}
|
|
301
|
-
if (!this.selectedDefinitions.length) {
|
|
302
|
-
this.log.debug('Skipping poll because no domains are selected.');
|
|
303
|
-
return;
|
|
304
|
-
}
|
|
305
|
-
const query = this.buildQuery(this.selectedDefinitions);
|
|
306
|
-
if (!query) {
|
|
307
|
-
this.log.warn('No query could be built for the current selection.');
|
|
308
|
-
return;
|
|
309
|
-
}
|
|
310
|
-
try {
|
|
311
|
-
const data = await this.apolloClient.query(query);
|
|
312
|
-
this.logGraphQLResponse(data);
|
|
313
|
-
await this.applyData(data);
|
|
314
|
-
}
|
|
315
|
-
catch (error) {
|
|
316
|
-
if (error instanceof Error) {
|
|
317
|
-
throw new Error(`GraphQL error: ${error.message}`);
|
|
318
|
-
}
|
|
319
|
-
throw error;
|
|
320
|
-
}
|
|
321
|
-
}
|
|
322
|
-
buildQuery(definitions) {
|
|
323
|
-
const builder = new GraphQLSelectionBuilder();
|
|
324
|
-
for (const definition of definitions) {
|
|
325
|
-
builder.addSelections(definition.selection);
|
|
326
|
-
}
|
|
327
|
-
return builder.build();
|
|
328
|
-
}
|
|
329
|
-
async applyData(data) {
|
|
330
|
-
// Only check for CPU cores if metrics.cpu is selected
|
|
331
|
-
if (this.effectiveSelection.has('metrics.cpu')) {
|
|
332
|
-
await this.handleDynamicCpuCores(data);
|
|
333
|
-
}
|
|
334
|
-
// Only check for array disks if any array disk domain is selected
|
|
335
|
-
if (this.effectiveSelection.has('array.disks') ||
|
|
336
|
-
this.effectiveSelection.has('array.parities') ||
|
|
337
|
-
this.effectiveSelection.has('array.caches')) {
|
|
338
|
-
await this.handleDynamicArrayDisks(data);
|
|
339
|
-
}
|
|
340
|
-
// Only check for docker containers if docker.containers is selected
|
|
341
|
-
if (this.effectiveSelection.has('docker.containers')) {
|
|
342
|
-
await this.handleDynamicDockerContainers(data);
|
|
343
|
-
}
|
|
344
|
-
// Only check for shares if shares.list is selected
|
|
345
|
-
if (this.effectiveSelection.has('shares.list')) {
|
|
346
|
-
await this.handleDynamicShares(data);
|
|
347
|
-
}
|
|
348
|
-
// Only check for VMs if vms.list is selected
|
|
349
|
-
if (this.effectiveSelection.has('vms.list')) {
|
|
350
|
-
await this.handleDynamicVms(data);
|
|
351
|
-
}
|
|
139
|
+
// Handle dynamic resources
|
|
140
|
+
await this.dynamicResourceManager.handleDynamicCpuCores(data, this.effectiveSelection);
|
|
141
|
+
await this.dynamicResourceManager.handleDynamicArrayDisks(data, this.effectiveSelection);
|
|
142
|
+
await this.dynamicResourceManager.handleDynamicDockerContainers(data, this.effectiveSelection);
|
|
143
|
+
await this.dynamicResourceManager.handleDynamicShares(data, this.effectiveSelection);
|
|
144
|
+
await this.dynamicResourceManager.handleDynamicVms(data, this.effectiveSelection);
|
|
145
|
+
// Apply static definitions
|
|
352
146
|
for (const definition of this.selectedDefinitions) {
|
|
353
|
-
await this.applyDefinition(definition, data);
|
|
354
|
-
}
|
|
355
|
-
}
|
|
356
|
-
async initializeStaticStates(definitions) {
|
|
357
|
-
for (const definition of definitions) {
|
|
358
|
-
for (const mapping of definition.states) {
|
|
359
|
-
await this.writeState(mapping.id, mapping.common, null);
|
|
360
|
-
}
|
|
361
|
-
}
|
|
362
|
-
}
|
|
363
|
-
async handleDynamicCpuCores(data) {
|
|
364
|
-
// Only process CPU cores if metrics.cpu is selected
|
|
365
|
-
if (!this.effectiveSelection.has('metrics.cpu')) {
|
|
366
|
-
return;
|
|
367
|
-
}
|
|
368
|
-
const metrics = data.metrics;
|
|
369
|
-
if (!metrics?.cpu?.cpus) {
|
|
370
|
-
return;
|
|
371
|
-
}
|
|
372
|
-
const cores = metrics.cpu.cpus;
|
|
373
|
-
const coreCount = Array.isArray(cores) ? cores.length : 0;
|
|
374
|
-
// Create CPU core states on first detection or if core count changed
|
|
375
|
-
if (!this.cpuCoresDetected || this.cpuCoreCount !== coreCount) {
|
|
376
|
-
this.cpuCoreCount = coreCount;
|
|
377
|
-
this.cpuCoresDetected = true;
|
|
378
|
-
this.log.info(`Detected ${coreCount} CPU cores, creating states...`);
|
|
379
|
-
// Create core count state
|
|
380
|
-
await this.writeState('metrics.cpu.cores.count', { type: 'number', role: 'value', unit: '' }, coreCount);
|
|
381
|
-
// Create states for each CPU core
|
|
382
|
-
for (let i = 0; i < coreCount; i++) {
|
|
383
|
-
const corePrefix = `metrics.cpu.cores.${i}`;
|
|
384
|
-
// Create states for this core
|
|
385
|
-
await this.writeState(`${corePrefix}.percentTotal`, { type: 'number', role: 'value.percent', unit: '%' }, null);
|
|
386
|
-
await this.writeState(`${corePrefix}.percentUser`, { type: 'number', role: 'value.percent', unit: '%' }, null);
|
|
387
|
-
await this.writeState(`${corePrefix}.percentSystem`, { type: 'number', role: 'value.percent', unit: '%' }, null);
|
|
388
|
-
await this.writeState(`${corePrefix}.percentNice`, { type: 'number', role: 'value.percent', unit: '%' }, null);
|
|
389
|
-
await this.writeState(`${corePrefix}.percentIdle`, { type: 'number', role: 'value.percent', unit: '%' }, null);
|
|
390
|
-
await this.writeState(`${corePrefix}.percentIrq`, { type: 'number', role: 'value.percent', unit: '%' }, null);
|
|
391
|
-
}
|
|
392
|
-
}
|
|
393
|
-
// Update CPU core values
|
|
394
|
-
for (let i = 0; i < cores.length; i++) {
|
|
395
|
-
const core = cores[i];
|
|
396
|
-
const corePrefix = `metrics.cpu.cores.${i}`;
|
|
397
|
-
await this.setStateAsync(`${corePrefix}.percentTotal`, { val: this.toNumberOrNull(core.percentTotal), ack: true });
|
|
398
|
-
await this.setStateAsync(`${corePrefix}.percentUser`, { val: this.toNumberOrNull(core.percentUser), ack: true });
|
|
399
|
-
await this.setStateAsync(`${corePrefix}.percentSystem`, { val: this.toNumberOrNull(core.percentSystem), ack: true });
|
|
400
|
-
await this.setStateAsync(`${corePrefix}.percentNice`, { val: this.toNumberOrNull(core.percentNice), ack: true });
|
|
401
|
-
await this.setStateAsync(`${corePrefix}.percentIdle`, { val: this.toNumberOrNull(core.percentIdle), ack: true });
|
|
402
|
-
await this.setStateAsync(`${corePrefix}.percentIrq`, { val: this.toNumberOrNull(core.percentIrq), ack: true });
|
|
403
|
-
}
|
|
404
|
-
}
|
|
405
|
-
async handleDynamicArrayDisks(data) {
|
|
406
|
-
// Check if any array disk domains are selected
|
|
407
|
-
const hasDisks = this.effectiveSelection.has('array.disks');
|
|
408
|
-
const hasParities = this.effectiveSelection.has('array.parities');
|
|
409
|
-
const hasCaches = this.effectiveSelection.has('array.caches');
|
|
410
|
-
// Skip if no array disk domains are selected
|
|
411
|
-
if (!hasDisks && !hasParities && !hasCaches) {
|
|
412
|
-
return;
|
|
413
|
-
}
|
|
414
|
-
const array = data.array;
|
|
415
|
-
if (!array) {
|
|
416
|
-
return;
|
|
417
|
-
}
|
|
418
|
-
const disks = hasDisks && Array.isArray(array.disks) ? array.disks : [];
|
|
419
|
-
const parities = hasParities && Array.isArray(array.parities) ? array.parities : [];
|
|
420
|
-
const caches = hasCaches && Array.isArray(array.caches) ? array.caches : [];
|
|
421
|
-
const diskCount = hasDisks ? disks.length : this.diskCount;
|
|
422
|
-
const parityCount = hasParities ? parities.length : this.parityCount;
|
|
423
|
-
const cacheCount = hasCaches ? caches.length : this.cacheCount;
|
|
424
|
-
// Create or update disk states if needed
|
|
425
|
-
if (!this.arrayDisksDetected ||
|
|
426
|
-
(hasDisks && this.diskCount !== diskCount) ||
|
|
427
|
-
(hasParities && this.parityCount !== parityCount) ||
|
|
428
|
-
(hasCaches && this.cacheCount !== cacheCount)) {
|
|
429
|
-
if (hasDisks)
|
|
430
|
-
this.diskCount = diskCount;
|
|
431
|
-
if (hasParities)
|
|
432
|
-
this.parityCount = parityCount;
|
|
433
|
-
if (hasCaches)
|
|
434
|
-
this.cacheCount = cacheCount;
|
|
435
|
-
this.arrayDisksDetected = true;
|
|
436
|
-
this.log.info(`Detected array configuration: ${diskCount} data disks, ${parityCount} parity disks, ${cacheCount} cache disks`);
|
|
437
|
-
// Create count states only for selected domains
|
|
438
|
-
if (hasDisks) {
|
|
439
|
-
await this.writeState('array.disks.count', { type: 'number', role: 'value', unit: '' }, diskCount);
|
|
440
|
-
await this.createDiskStates('array.disks', disks);
|
|
441
|
-
}
|
|
442
|
-
if (hasParities) {
|
|
443
|
-
await this.writeState('array.parities.count', { type: 'number', role: 'value', unit: '' }, parityCount);
|
|
444
|
-
await this.createDiskStates('array.parities', parities);
|
|
445
|
-
}
|
|
446
|
-
if (hasCaches) {
|
|
447
|
-
await this.writeState('array.caches.count', { type: 'number', role: 'value', unit: '' }, cacheCount);
|
|
448
|
-
await this.createDiskStates('array.caches', caches);
|
|
449
|
-
}
|
|
450
|
-
}
|
|
451
|
-
// Update disk values only for selected domains
|
|
452
|
-
if (hasDisks && disks.length > 0) {
|
|
453
|
-
await this.updateDiskValues('array.disks', disks);
|
|
454
|
-
}
|
|
455
|
-
if (hasParities && parities.length > 0) {
|
|
456
|
-
await this.updateDiskValues('array.parities', parities);
|
|
457
|
-
}
|
|
458
|
-
if (hasCaches && caches.length > 0) {
|
|
459
|
-
await this.updateDiskValues('array.caches', caches);
|
|
460
|
-
}
|
|
461
|
-
}
|
|
462
|
-
async createDiskStates(prefix, disks) {
|
|
463
|
-
for (let i = 0; i < disks.length; i++) {
|
|
464
|
-
const disk = disks[i];
|
|
465
|
-
const diskPrefix = `${prefix}.${disk.idx ?? i}`;
|
|
466
|
-
// Basic info states
|
|
467
|
-
await this.writeState(`${diskPrefix}.name`, { type: 'string', role: 'text' }, null);
|
|
468
|
-
await this.writeState(`${diskPrefix}.device`, { type: 'string', role: 'text' }, null);
|
|
469
|
-
await this.writeState(`${diskPrefix}.status`, { type: 'string', role: 'indicator.status' }, null);
|
|
470
|
-
await this.writeState(`${diskPrefix}.temp`, { type: 'number', role: 'value.temperature', unit: '°C' }, null);
|
|
471
|
-
await this.writeState(`${diskPrefix}.type`, { type: 'string', role: 'text' }, null);
|
|
472
|
-
// Size states
|
|
473
|
-
await this.writeState(`${diskPrefix}.sizeGb`, { type: 'number', role: 'value', unit: 'GB' }, null);
|
|
474
|
-
await this.writeState(`${diskPrefix}.fsSizeGb`, { type: 'number', role: 'value', unit: 'GB' }, null);
|
|
475
|
-
await this.writeState(`${diskPrefix}.fsUsedGb`, { type: 'number', role: 'value', unit: 'GB' }, null);
|
|
476
|
-
await this.writeState(`${diskPrefix}.fsFreeGb`, { type: 'number', role: 'value', unit: 'GB' }, null);
|
|
477
|
-
await this.writeState(`${diskPrefix}.fsUsedPercent`, { type: 'number', role: 'value.percent', unit: '%' }, null);
|
|
478
|
-
// File system info
|
|
479
|
-
await this.writeState(`${diskPrefix}.fsType`, { type: 'string', role: 'text' }, null);
|
|
480
|
-
await this.writeState(`${diskPrefix}.isSpinning`, { type: 'boolean', role: 'indicator' }, null);
|
|
481
|
-
// Performance counters
|
|
482
|
-
await this.writeState(`${diskPrefix}.numReads`, { type: 'number', role: 'value' }, null);
|
|
483
|
-
await this.writeState(`${diskPrefix}.numWrites`, { type: 'number', role: 'value' }, null);
|
|
484
|
-
await this.writeState(`${diskPrefix}.numErrors`, { type: 'number', role: 'value' }, null);
|
|
485
|
-
// Temperature thresholds
|
|
486
|
-
await this.writeState(`${diskPrefix}.warning`, { type: 'number', role: 'value.temperature', unit: '°C' }, null);
|
|
487
|
-
await this.writeState(`${diskPrefix}.critical`, { type: 'number', role: 'value.temperature', unit: '°C' }, null);
|
|
488
|
-
// Additional info
|
|
489
|
-
await this.writeState(`${diskPrefix}.rotational`, { type: 'boolean', role: 'indicator' }, null);
|
|
490
|
-
await this.writeState(`${diskPrefix}.transport`, { type: 'string', role: 'text' }, null);
|
|
491
|
-
}
|
|
492
|
-
}
|
|
493
|
-
async updateDiskValues(prefix, disks) {
|
|
494
|
-
for (const disk of disks) {
|
|
495
|
-
const d = disk;
|
|
496
|
-
const diskPrefix = `${prefix}.${d.idx ?? disks.indexOf(disk)}`;
|
|
497
|
-
await this.setStateAsync(`${diskPrefix}.name`, { val: this.toStringOrNull(d.name), ack: true });
|
|
498
|
-
await this.setStateAsync(`${diskPrefix}.device`, { val: this.toStringOrNull(d.device), ack: true });
|
|
499
|
-
await this.setStateAsync(`${diskPrefix}.status`, { val: this.toStringOrNull(d.status), ack: true });
|
|
500
|
-
await this.setStateAsync(`${diskPrefix}.temp`, { val: this.toNumberOrNull(d.temp), ack: true });
|
|
501
|
-
await this.setStateAsync(`${diskPrefix}.type`, { val: this.toStringOrNull(d.type), ack: true });
|
|
502
|
-
// Convert KB to GB for sizes
|
|
503
|
-
await this.setStateAsync(`${diskPrefix}.sizeGb`, { val: this.kilobytesToGigabytes(d.size), ack: true });
|
|
504
|
-
await this.setStateAsync(`${diskPrefix}.fsSizeGb`, { val: this.kilobytesToGigabytes(d.fsSize), ack: true });
|
|
505
|
-
await this.setStateAsync(`${diskPrefix}.fsUsedGb`, { val: this.kilobytesToGigabytes(d.fsUsed), ack: true });
|
|
506
|
-
await this.setStateAsync(`${diskPrefix}.fsFreeGb`, { val: this.kilobytesToGigabytes(d.fsFree), ack: true });
|
|
507
|
-
// Calculate and set fsUsedPercent
|
|
508
|
-
const fsUsedPercent = this.calculateUsagePercent(d.fsUsed, d.fsSize);
|
|
509
|
-
await this.setStateAsync(`${diskPrefix}.fsUsedPercent`, { val: fsUsedPercent, ack: true });
|
|
510
|
-
await this.setStateAsync(`${diskPrefix}.fsType`, { val: this.toStringOrNull(d.fsType), ack: true });
|
|
511
|
-
await this.setStateAsync(`${diskPrefix}.isSpinning`, { val: this.toBooleanOrNull(d.isSpinning), ack: true });
|
|
512
|
-
// BigInt handling for counters
|
|
513
|
-
await this.setStateAsync(`${diskPrefix}.numReads`, { val: this.bigIntToNumber(d.numReads), ack: true });
|
|
514
|
-
await this.setStateAsync(`${diskPrefix}.numWrites`, { val: this.bigIntToNumber(d.numWrites), ack: true });
|
|
515
|
-
await this.setStateAsync(`${diskPrefix}.numErrors`, { val: this.bigIntToNumber(d.numErrors), ack: true });
|
|
516
|
-
await this.setStateAsync(`${diskPrefix}.warning`, { val: this.toNumberOrNull(d.warning), ack: true });
|
|
517
|
-
await this.setStateAsync(`${diskPrefix}.critical`, { val: this.toNumberOrNull(d.critical), ack: true });
|
|
518
|
-
await this.setStateAsync(`${diskPrefix}.rotational`, { val: this.toBooleanOrNull(d.rotational), ack: true });
|
|
519
|
-
await this.setStateAsync(`${diskPrefix}.transport`, { val: this.toStringOrNull(d.transport), ack: true });
|
|
520
|
-
}
|
|
521
|
-
}
|
|
522
|
-
kilobytesToGigabytes(value) {
|
|
523
|
-
const numeric = this.toNumberOrNull(value);
|
|
524
|
-
if (numeric === null) {
|
|
525
|
-
return null;
|
|
526
|
-
}
|
|
527
|
-
const gb = numeric / (1024 * 1024);
|
|
528
|
-
return Number.isFinite(gb) ? Math.round(gb * 100) / 100 : null;
|
|
529
|
-
}
|
|
530
|
-
bytesToGigabytes(value) {
|
|
531
|
-
const numeric = this.toNumberOrNull(value);
|
|
532
|
-
if (numeric === null) {
|
|
533
|
-
return null;
|
|
534
|
-
}
|
|
535
|
-
const gb = numeric / (1024 * 1024 * 1024);
|
|
536
|
-
return Number.isFinite(gb) ? Math.round(gb * 100) / 100 : null;
|
|
537
|
-
}
|
|
538
|
-
calculateUsagePercent(used, total) {
|
|
539
|
-
const usedNumeric = this.toNumberOrNull(used);
|
|
540
|
-
const totalNumeric = this.toNumberOrNull(total);
|
|
541
|
-
// Return null if either value is null or total is 0
|
|
542
|
-
if (usedNumeric === null || totalNumeric === null || totalNumeric === 0) {
|
|
543
|
-
return null;
|
|
544
|
-
}
|
|
545
|
-
const percent = (usedNumeric / totalNumeric) * 100;
|
|
546
|
-
return Number.isFinite(percent) ? Math.round(percent * 100) / 100 : null;
|
|
547
|
-
}
|
|
548
|
-
async handleDynamicDockerContainers(data) {
|
|
549
|
-
// Only process docker containers if docker.containers is selected
|
|
550
|
-
if (!this.effectiveSelection.has('docker.containers')) {
|
|
551
|
-
return;
|
|
552
|
-
}
|
|
553
|
-
const docker = data.docker;
|
|
554
|
-
if (!docker?.containers) {
|
|
555
|
-
return;
|
|
556
|
-
}
|
|
557
|
-
const containers = Array.isArray(docker.containers) ? docker.containers : [];
|
|
558
|
-
const containerNames = new Set();
|
|
559
|
-
for (const container of containers) {
|
|
560
|
-
const c = container;
|
|
561
|
-
const names = c.names;
|
|
562
|
-
if (names && Array.isArray(names) && names.length > 0) {
|
|
563
|
-
// Use first name, remove leading slash
|
|
564
|
-
const name = names[0].replace(/^\//, '');
|
|
565
|
-
containerNames.add(name);
|
|
566
|
-
}
|
|
567
|
-
}
|
|
568
|
-
// Check if we need to create new container states
|
|
569
|
-
const needsUpdate = !this.dockerContainersDetected ||
|
|
570
|
-
containerNames.size !== this.containerNames.size ||
|
|
571
|
-
![...containerNames].every(name => this.containerNames.has(name));
|
|
572
|
-
if (needsUpdate) {
|
|
573
|
-
this.containerNames = containerNames;
|
|
574
|
-
this.dockerContainersDetected = true;
|
|
575
|
-
this.log.info(`Detected ${containerNames.size} Docker containers`);
|
|
576
|
-
// Create container count state
|
|
577
|
-
await this.writeState('docker.containers.count', { type: 'number', role: 'value', unit: '' }, containerNames.size);
|
|
578
|
-
// Create states for each container
|
|
579
|
-
for (const container of containers) {
|
|
580
|
-
const c = container;
|
|
581
|
-
const names = c.names;
|
|
582
|
-
if (!names || !Array.isArray(names) || names.length === 0)
|
|
583
|
-
continue;
|
|
584
|
-
const name = names[0].replace(/^\//, '');
|
|
585
|
-
const containerPrefix = `docker.containers.${name.replace(/[^a-zA-Z0-9_-]/g, '_')}`;
|
|
586
|
-
await this.writeState(`${containerPrefix}.name`, { type: 'string', role: 'text' }, null);
|
|
587
|
-
await this.writeState(`${containerPrefix}.image`, { type: 'string', role: 'text' }, null);
|
|
588
|
-
await this.writeState(`${containerPrefix}.state`, { type: 'string', role: 'indicator.status' }, null);
|
|
589
|
-
await this.writeState(`${containerPrefix}.status`, { type: 'string', role: 'text' }, null);
|
|
590
|
-
await this.writeState(`${containerPrefix}.autoStart`, { type: 'boolean', role: 'indicator' }, null);
|
|
591
|
-
await this.writeState(`${containerPrefix}.sizeGb`, { type: 'number', role: 'value', unit: 'GB' }, null);
|
|
592
|
-
}
|
|
593
|
-
}
|
|
594
|
-
// Update container values - only for containers we're tracking
|
|
595
|
-
for (const container of containers) {
|
|
596
|
-
const c = container;
|
|
597
|
-
const names = c.names;
|
|
598
|
-
if (!names || !Array.isArray(names) || names.length === 0)
|
|
599
|
-
continue;
|
|
600
|
-
const name = names[0].replace(/^\//, '');
|
|
601
|
-
// Only update if we're still tracking this container
|
|
602
|
-
if (!this.containerNames.has(name)) {
|
|
603
|
-
continue;
|
|
604
|
-
}
|
|
605
|
-
const containerPrefix = `docker.containers.${name.replace(/[^a-zA-Z0-9_-]/g, '_')}`;
|
|
606
|
-
await this.setStateAsync(`${containerPrefix}.name`, { val: name, ack: true });
|
|
607
|
-
await this.setStateAsync(`${containerPrefix}.image`, { val: this.toStringOrNull(c.image), ack: true });
|
|
608
|
-
await this.setStateAsync(`${containerPrefix}.state`, { val: this.toStringOrNull(c.state), ack: true });
|
|
609
|
-
await this.setStateAsync(`${containerPrefix}.status`, { val: this.toStringOrNull(c.status), ack: true });
|
|
610
|
-
await this.setStateAsync(`${containerPrefix}.autoStart`, { val: this.toBooleanOrNull(c.autoStart), ack: true });
|
|
611
|
-
await this.setStateAsync(`${containerPrefix}.sizeGb`, { val: this.bytesToGigabytes(c.sizeRootFs), ack: true });
|
|
612
|
-
}
|
|
613
|
-
}
|
|
614
|
-
async handleDynamicShares(data) {
|
|
615
|
-
// Only process shares if shares.list is selected
|
|
616
|
-
if (!this.effectiveSelection.has('shares.list')) {
|
|
617
|
-
return;
|
|
618
|
-
}
|
|
619
|
-
const shares = data.shares;
|
|
620
|
-
if (!shares || !Array.isArray(shares)) {
|
|
621
|
-
return;
|
|
622
|
-
}
|
|
623
|
-
const shareNames = new Set();
|
|
624
|
-
for (const share of shares) {
|
|
625
|
-
const s = share;
|
|
626
|
-
const name = s.name;
|
|
627
|
-
if (name) {
|
|
628
|
-
shareNames.add(name);
|
|
629
|
-
}
|
|
630
|
-
}
|
|
631
|
-
// Check if we need to create new share states
|
|
632
|
-
const needsUpdate = !this.sharesDetected ||
|
|
633
|
-
shareNames.size !== this.shareNames.size ||
|
|
634
|
-
![...shareNames].every(name => this.shareNames.has(name));
|
|
635
|
-
if (needsUpdate) {
|
|
636
|
-
this.shareNames = shareNames;
|
|
637
|
-
this.sharesDetected = true;
|
|
638
|
-
this.log.info(`Detected ${shareNames.size} shares`);
|
|
639
|
-
// Create share count state
|
|
640
|
-
await this.writeState('shares.count', { type: 'number', role: 'value', unit: '' }, shareNames.size);
|
|
641
|
-
// Create states for each share
|
|
642
|
-
for (const share of shares) {
|
|
643
|
-
const s = share;
|
|
644
|
-
const name = s.name;
|
|
645
|
-
if (!name)
|
|
646
|
-
continue;
|
|
647
|
-
const sharePrefix = `shares.${name.replace(/[^a-zA-Z0-9_-]/g, '_')}`;
|
|
648
|
-
await this.writeState(`${sharePrefix}.name`, { type: 'string', role: 'text' }, null);
|
|
649
|
-
await this.writeState(`${sharePrefix}.freeGb`, { type: 'number', role: 'value', unit: 'GB' }, null);
|
|
650
|
-
await this.writeState(`${sharePrefix}.usedGb`, { type: 'number', role: 'value', unit: 'GB' }, null);
|
|
651
|
-
await this.writeState(`${sharePrefix}.sizeGb`, { type: 'number', role: 'value', unit: 'GB' }, null);
|
|
652
|
-
await this.writeState(`${sharePrefix}.usedPercent`, { type: 'number', role: 'value.percent', unit: '%' }, null);
|
|
653
|
-
await this.writeState(`${sharePrefix}.comment`, { type: 'string', role: 'text' }, null);
|
|
654
|
-
await this.writeState(`${sharePrefix}.allocator`, { type: 'string', role: 'text' }, null);
|
|
655
|
-
await this.writeState(`${sharePrefix}.cow`, { type: 'string', role: 'text' }, null);
|
|
656
|
-
await this.writeState(`${sharePrefix}.color`, { type: 'string', role: 'text' }, null);
|
|
657
|
-
}
|
|
658
|
-
}
|
|
659
|
-
// Update share values - only for shares we're tracking
|
|
660
|
-
for (const share of shares) {
|
|
661
|
-
const s = share;
|
|
662
|
-
const name = s.name;
|
|
663
|
-
if (!name)
|
|
664
|
-
continue;
|
|
665
|
-
// Only update if we're still tracking this share
|
|
666
|
-
if (!this.shareNames.has(name)) {
|
|
667
|
-
continue;
|
|
668
|
-
}
|
|
669
|
-
const sharePrefix = `shares.${name.replace(/[^a-zA-Z0-9_-]/g, '_')}`;
|
|
670
|
-
await this.setStateAsync(`${sharePrefix}.name`, { val: name, ack: true });
|
|
671
|
-
await this.setStateAsync(`${sharePrefix}.freeGb`, { val: this.kilobytesToGigabytes(s.free), ack: true });
|
|
672
|
-
await this.setStateAsync(`${sharePrefix}.usedGb`, { val: this.kilobytesToGigabytes(s.used), ack: true });
|
|
673
|
-
await this.setStateAsync(`${sharePrefix}.sizeGb`, { val: this.kilobytesToGigabytes(s.size), ack: true });
|
|
674
|
-
// Calculate usage percent (used / (used + free))
|
|
675
|
-
const usedKb = this.toNumberOrNull(s.used);
|
|
676
|
-
const freeKb = this.toNumberOrNull(s.free);
|
|
677
|
-
let usedPercent = null;
|
|
678
|
-
if (usedKb !== null && freeKb !== null && (usedKb + freeKb) > 0) {
|
|
679
|
-
usedPercent = Math.round((usedKb / (usedKb + freeKb)) * 10000) / 100;
|
|
680
|
-
}
|
|
681
|
-
await this.setStateAsync(`${sharePrefix}.usedPercent`, { val: usedPercent, ack: true });
|
|
682
|
-
await this.setStateAsync(`${sharePrefix}.comment`, { val: this.toStringOrNull(s.comment), ack: true });
|
|
683
|
-
await this.setStateAsync(`${sharePrefix}.allocator`, { val: this.toStringOrNull(s.allocator), ack: true });
|
|
684
|
-
await this.setStateAsync(`${sharePrefix}.cow`, { val: this.toStringOrNull(s.cow), ack: true });
|
|
685
|
-
await this.setStateAsync(`${sharePrefix}.color`, { val: this.toStringOrNull(s.color), ack: true });
|
|
686
|
-
}
|
|
687
|
-
}
|
|
688
|
-
async handleDynamicVms(data) {
|
|
689
|
-
// Only process VMs if vms.list is selected
|
|
690
|
-
if (!this.effectiveSelection.has('vms.list')) {
|
|
691
|
-
return;
|
|
692
|
-
}
|
|
693
|
-
const vms = data.vms;
|
|
694
|
-
if (!vms?.domains) {
|
|
695
|
-
return;
|
|
696
|
-
}
|
|
697
|
-
const domains = Array.isArray(vms.domains) ? vms.domains : [];
|
|
698
|
-
const vmUuids = new Set();
|
|
699
|
-
for (const vm of domains) {
|
|
700
|
-
const v = vm;
|
|
701
|
-
const uuid = v.uuid;
|
|
702
|
-
if (uuid) {
|
|
703
|
-
vmUuids.add(uuid);
|
|
704
|
-
}
|
|
705
|
-
}
|
|
706
|
-
// Check if we need to create new VM states
|
|
707
|
-
const needsUpdate = !this.vmsDetected ||
|
|
708
|
-
vmUuids.size !== this.vmUuids.size ||
|
|
709
|
-
![...vmUuids].every(uuid => this.vmUuids.has(uuid));
|
|
710
|
-
if (needsUpdate) {
|
|
711
|
-
this.vmUuids = vmUuids;
|
|
712
|
-
this.vmsDetected = true;
|
|
713
|
-
this.log.info(`Detected ${vmUuids.size} VMs`);
|
|
714
|
-
// Create VM count state
|
|
715
|
-
await this.writeState('vms.count', { type: 'number', role: 'value', unit: '' }, vmUuids.size);
|
|
716
|
-
// Create states for each VM
|
|
717
|
-
for (const vm of domains) {
|
|
718
|
-
const v = vm;
|
|
719
|
-
const name = v.name;
|
|
720
|
-
const uuid = v.uuid;
|
|
721
|
-
if (!name || !uuid)
|
|
722
|
-
continue;
|
|
723
|
-
const vmPrefix = `vms.${name.replace(/[^a-zA-Z0-9_-]/g, '_')}`;
|
|
724
|
-
await this.writeState(`${vmPrefix}.name`, { type: 'string', role: 'text' }, null);
|
|
725
|
-
await this.writeState(`${vmPrefix}.state`, { type: 'string', role: 'indicator.status' }, null);
|
|
726
|
-
await this.writeState(`${vmPrefix}.uuid`, { type: 'string', role: 'text' }, null);
|
|
727
|
-
}
|
|
728
|
-
}
|
|
729
|
-
// Update VM values - only for VMs we're tracking
|
|
730
|
-
for (const vm of domains) {
|
|
731
|
-
const v = vm;
|
|
732
|
-
const name = v.name;
|
|
733
|
-
const uuid = v.uuid;
|
|
734
|
-
if (!name || !uuid)
|
|
735
|
-
continue;
|
|
736
|
-
// Only update if we're still tracking this VM
|
|
737
|
-
if (!this.vmUuids.has(uuid)) {
|
|
738
|
-
continue;
|
|
739
|
-
}
|
|
740
|
-
const vmPrefix = `vms.${name.replace(/[^a-zA-Z0-9_-]/g, '_')}`;
|
|
741
|
-
await this.setStateAsync(`${vmPrefix}.name`, { val: name, ack: true });
|
|
742
|
-
await this.setStateAsync(`${vmPrefix}.state`, { val: this.toStringOrNull(v.state), ack: true });
|
|
743
|
-
await this.setStateAsync(`${vmPrefix}.uuid`, { val: uuid, ack: true });
|
|
744
|
-
}
|
|
745
|
-
}
|
|
746
|
-
bigIntToNumber(value) {
|
|
747
|
-
if (value === null || value === undefined) {
|
|
748
|
-
return null;
|
|
749
|
-
}
|
|
750
|
-
if (typeof value === 'bigint') {
|
|
751
|
-
const num = Number(value);
|
|
752
|
-
return Number.isFinite(num) ? num : null;
|
|
753
|
-
}
|
|
754
|
-
return this.toNumberOrNull(value);
|
|
755
|
-
}
|
|
756
|
-
toStringOrNull(value) {
|
|
757
|
-
if (value === null || value === undefined) {
|
|
758
|
-
return null;
|
|
759
|
-
}
|
|
760
|
-
if (typeof value === 'string') {
|
|
761
|
-
return value;
|
|
762
|
-
}
|
|
763
|
-
if (typeof value === 'number' || typeof value === 'boolean') {
|
|
764
|
-
return String(value);
|
|
765
|
-
}
|
|
766
|
-
return null;
|
|
767
|
-
}
|
|
768
|
-
toBooleanOrNull(value) {
|
|
769
|
-
if (value === null || value === undefined) {
|
|
770
|
-
return null;
|
|
771
|
-
}
|
|
772
|
-
if (typeof value === 'boolean') {
|
|
773
|
-
return value;
|
|
774
|
-
}
|
|
775
|
-
return null;
|
|
776
|
-
}
|
|
777
|
-
toNumberOrNull(value) {
|
|
778
|
-
if (value === null || value === undefined) {
|
|
779
|
-
return null;
|
|
780
|
-
}
|
|
781
|
-
if (typeof value === 'number') {
|
|
782
|
-
return Number.isFinite(value) ? value : null;
|
|
783
|
-
}
|
|
784
|
-
if (typeof value === 'string') {
|
|
785
|
-
const parsed = Number(value);
|
|
786
|
-
return Number.isFinite(parsed) ? parsed : null;
|
|
787
|
-
}
|
|
788
|
-
return null;
|
|
789
|
-
}
|
|
790
|
-
async applyDefinition(definition, data) {
|
|
791
|
-
// First check if this domain's data exists in the result
|
|
792
|
-
const rootPath = definition.selection[0]?.root;
|
|
793
|
-
if (!rootPath || !(rootPath in data)) {
|
|
794
|
-
// Skip if this domain wasn't queried
|
|
795
|
-
return;
|
|
796
|
-
}
|
|
797
|
-
for (const mapping of definition.states) {
|
|
798
|
-
const rawValue = this.resolveValue(data, mapping.path);
|
|
799
|
-
const transformed = mapping.transform ? mapping.transform(rawValue) : rawValue;
|
|
800
|
-
await this.writeState(mapping.id, mapping.common, transformed);
|
|
801
|
-
}
|
|
802
|
-
}
|
|
803
|
-
resolveValue(source, path) {
|
|
804
|
-
let current = source;
|
|
805
|
-
for (const segment of path) {
|
|
806
|
-
if (!current || typeof current !== 'object') {
|
|
807
|
-
return null;
|
|
808
|
-
}
|
|
809
|
-
current = current[segment];
|
|
810
|
-
}
|
|
811
|
-
return current === undefined ? null : current;
|
|
812
|
-
}
|
|
813
|
-
async cleanupObjectTree(allowedIds) {
|
|
814
|
-
const objects = await this.getAdapterObjectsAsync();
|
|
815
|
-
for (const fullId of Object.keys(objects)) {
|
|
816
|
-
const relativeId = fullId.startsWith(`${this.namespace}.`)
|
|
817
|
-
? fullId.slice(this.namespace.length + 1)
|
|
818
|
-
: fullId;
|
|
819
|
-
if (!relativeId) {
|
|
820
|
-
continue;
|
|
821
|
-
}
|
|
822
|
-
if (!this.shouldKeepObject(relativeId, allowedIds)) {
|
|
823
|
-
try {
|
|
824
|
-
await this.delObjectAsync(relativeId, { recursive: true });
|
|
825
|
-
}
|
|
826
|
-
catch (error) {
|
|
827
|
-
this.log.warn(`Failed to remove object ${relativeId}: ${this.describeError(error)}`);
|
|
828
|
-
}
|
|
829
|
-
}
|
|
830
|
-
}
|
|
831
|
-
this.createdChannels.clear();
|
|
832
|
-
this.createdStates.clear();
|
|
833
|
-
}
|
|
834
|
-
shouldKeepObject(objectId, allowedIds) {
|
|
835
|
-
if (allowedIds.has(objectId)) {
|
|
836
|
-
return true;
|
|
837
|
-
}
|
|
838
|
-
const parts = objectId.split('.');
|
|
839
|
-
for (let index = parts.length - 1; index > 0; index -= 1) {
|
|
840
|
-
const candidate = parts.slice(0, index).join('.');
|
|
841
|
-
if (allowedIds.has(candidate)) {
|
|
842
|
-
return true;
|
|
843
|
-
}
|
|
844
|
-
}
|
|
845
|
-
return false;
|
|
846
|
-
}
|
|
847
|
-
async ensureChannelHierarchy(id) {
|
|
848
|
-
const parts = id.split('.');
|
|
849
|
-
for (let index = 1; index < parts.length; index += 1) {
|
|
850
|
-
const channelId = parts.slice(0, index).join('.');
|
|
851
|
-
if (this.createdChannels.has(channelId)) {
|
|
852
|
-
continue;
|
|
853
|
-
}
|
|
854
|
-
const labelKey = unraid_domains_1.domainNodeById.get(channelId)?.label ?? channelId;
|
|
855
|
-
await this.setObjectNotExistsAsync(channelId, {
|
|
856
|
-
type: 'channel',
|
|
857
|
-
common: {
|
|
858
|
-
name: labelKey,
|
|
859
|
-
},
|
|
860
|
-
native: {},
|
|
861
|
-
});
|
|
862
|
-
this.createdChannels.add(channelId);
|
|
863
|
-
}
|
|
864
|
-
}
|
|
865
|
-
async writeState(id, common, value) {
|
|
866
|
-
await this.ensureChannelHierarchy(id);
|
|
867
|
-
if (!this.createdStates.has(id)) {
|
|
868
|
-
await this.setObjectNotExistsAsync(id, {
|
|
869
|
-
type: 'state',
|
|
870
|
-
common: {
|
|
871
|
-
name: id,
|
|
872
|
-
role: common.role,
|
|
873
|
-
type: common.type,
|
|
874
|
-
unit: common.unit,
|
|
875
|
-
read: true,
|
|
876
|
-
write: false,
|
|
877
|
-
},
|
|
878
|
-
native: {},
|
|
879
|
-
});
|
|
880
|
-
this.createdStates.add(id);
|
|
881
|
-
}
|
|
882
|
-
const normalizedValue = value === undefined ? null : value;
|
|
883
|
-
await this.setStateAsync(id, { val: normalizedValue, ack: true });
|
|
884
|
-
}
|
|
885
|
-
logGraphQLResponse(data) {
|
|
886
|
-
try {
|
|
887
|
-
const serialized = JSON.stringify(data);
|
|
888
|
-
const maxLength = 3000;
|
|
889
|
-
const output = serialized.length > maxLength ? `${serialized.slice(0, maxLength)}…` : serialized;
|
|
890
|
-
this.log.debug(`GraphQL response: ${output}`);
|
|
891
|
-
}
|
|
892
|
-
catch (error) {
|
|
893
|
-
this.log.debug(`GraphQL response received but could not be stringified: ${this.describeError(error)}`);
|
|
147
|
+
await this.stateManager.applyDefinition(definition, data);
|
|
894
148
|
}
|
|
895
149
|
}
|
|
896
150
|
onStateChange(id, state) {
|
|
@@ -905,30 +159,22 @@ class UnraidAdapter extends adapter_core_1.Adapter {
|
|
|
905
159
|
return String(error);
|
|
906
160
|
}
|
|
907
161
|
onUnload(callback) {
|
|
908
|
-
this.stopRequested = true;
|
|
909
162
|
try {
|
|
910
|
-
//
|
|
911
|
-
|
|
912
|
-
this.clearTimeout(this.pollTimer);
|
|
913
|
-
this.pollTimer = undefined;
|
|
914
|
-
}
|
|
915
|
-
// Stop subscriptions if active (fire and forget)
|
|
916
|
-
if (this.subscriptionManager) {
|
|
917
|
-
this.subscriptionManager.stop()
|
|
918
|
-
.catch((error) => {
|
|
919
|
-
this.log.warn(`Failed to stop subscriptions: ${this.describeError(error)}`);
|
|
920
|
-
});
|
|
921
|
-
this.subscriptionManager = undefined;
|
|
922
|
-
}
|
|
163
|
+
// Stop polling
|
|
164
|
+
this.pollingManager?.stop();
|
|
923
165
|
// Dispose Apollo client (fire and forget)
|
|
924
166
|
if (this.apolloClient) {
|
|
925
|
-
this.apolloClient.dispose()
|
|
926
|
-
.catch((error) => {
|
|
167
|
+
this.apolloClient.dispose().catch(error => {
|
|
927
168
|
this.log.warn(`Failed to dispose Apollo client: ${this.describeError(error)}`);
|
|
928
169
|
});
|
|
929
170
|
this.apolloClient = undefined;
|
|
930
171
|
}
|
|
931
|
-
|
|
172
|
+
// Clear managers
|
|
173
|
+
this.stateManager?.clear();
|
|
174
|
+
this.stateManager = undefined;
|
|
175
|
+
this.dynamicResourceManager = undefined;
|
|
176
|
+
this.pollingManager = undefined;
|
|
177
|
+
this.log.debug('Adapter cleanup completed');
|
|
932
178
|
}
|
|
933
179
|
catch (error) {
|
|
934
180
|
this.log.error(`Error during adapter cleanup: ${this.describeError(error)}`);
|