-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathSoftware Obsolescence Management workflow 1.2.0 (Refresh Data & Alert).yaml
743 lines (686 loc) · 38.9 KB
/
Software Obsolescence Management workflow 1.2.0 (Refresh Data & Alert).yaml
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
metadata:
version: "1"
dependencies:
apps:
- id: dynatrace.automations
version: ^1.1547.1
inputs: []
workflow:
title: Software Obsolescence Management workflow 1.2.0 (Refresh Data & Alert)
tasks:
run_javascript_1:
name: run_javascript_1
description: Build a custom task running js Code
action: dynatrace.automations:run-javascript
input:
script: >-
import { eventsClient } from
'@dynatrace-sdk/client-classic-environment-v2';
import { queryExecutionClient } from "@dynatrace-sdk/client-query";
//--------------------------------- ↓ User configuration of the
proactive alerting system ↓ ---------------------------------
/*
* Enable/disable the pre-defined thresholds - in amount of remaining
days before obsolescence - which to raise Davis events for.
* Possible values are 'CUSTOM_INFO', 'CUSTOM_ALERT' and false. Do NOT
modify the two possible thresholds keys (eg. '0' and '30').
*/
const alertThresholds = {
'0': 'CUSTOM_INFO',
'30': 'CUSTOM_INFO'
}
/*
* You can define a list of management zones by their full name to
restrict the alerting to specific perimeters.
* If the workflow detects the upcoming obsolescence of operating
systems running in your environment,
* it will only act on the previously-defined thresholds if at least
one of the host's management zones is part of this list.
* It will not act on the previously-defined thresholds if none of the
host's management zones is part of this list.
* No management zone restriction applies if this list is an empty
array:
*/
const alertManagementZoneRestrictions = [
// '[MyApp] Infra layer',
// 'Special MZ 208569',
// 'NORAM overview',
]
/*
* Same concept applies for tags:
*/
const alertTagRestrictions = [
// 'stage:prod',
// 'K8host:d1-eks-demo',
// 'kubernetes',
]
/*
* Note: the combination of both a list of management zone(s) and
tag(s) is restrictive.
* This means that only entities respecting *both* types of
restrictions will be included in the obsolesence analysis
*/
/*
* Update the overrides constant below with your own OS support
extensions or end of life documentation
* For operating systems, use the Full Name as key and define the
extended support date (YYYY-MM-DD)
* You can review below a few commented examples of support extension
definition
*/
const supportOverrides = {
// 'Linux - Debian GNU/Linux 10 (buster) (kernel 5.10.233-224.894.amzn2.x86_64)': '2026-09-10',
// 'Debian GNU/Linux 12 (bookworm) (kernel 6.1.0-25-cloud-amd64)': '2026-10-30',
// 'Ubuntu 18.04.6 LTS (Bionic Beaver) (kernel 5.4.0-1089-azure)': '2026-10-30',
// 'Container-Optimized OS 113 (kernel 6.1.123+)': '2025-10-30',
// 'Amazon Linux 2 (kernel 5.10.197-186.748.amzn2.x86_64)': '2025-04-03'
};
//--------------------------------- End of user configuration of the
proactive alerting system ---------------------------------
//--------------------------------- ↓ Only modify the code section
below if you fully understand how the workflow's code and dashboard's
DQL are working together ↓ ---------------------------------
//--------------------------------- ↓ Raise proactive alerts ↓
---------------------------------
async function raiseProactiveAlerts() {
if(Object.keys(alertThresholds).find(e => alertThresholds[e] !== false && alertThresholds[e] !== 'false')) { // Launch the worker only if there's at least one threshold activated (cf. constants above)
console.log('Launching the obsolescence alerting worker...')
const overridesVariableArray = [];
for(let override of Object.keys(supportOverrides)) {
const overridesVariable = {};
overridesVariable[override] = supportOverrides[override];
overridesVariableArray.push(JSON.stringify(overridesVariable).replace(/"/g, "'"));
}
console.log('Support overrides:')
console.log(overridesVariableArray.map(e => `"${e}"`).join(','));
try {
const query = {
body: {
query: 'fetch dt.entity.host, from: -15m | fieldsAdd osVersion, managementZones, hostGroupName, tags, softwareObsolescenceManagement = entity.name | filter isNotNull(osVersion) | fieldsAdd result = lookup([ fetch events, from: -7d | filter dt.system.bucket == "default_davis_custom_events" | filter event.name == "software-obsolescence-management.os-info" | sort timestamp DESC ], sourceField:osVersion, lookupField:key ) | fieldsFlatten result, prefix:"event." | fieldsAdd `Extended Support` = if( ((indexOf(toString(array(' +
overridesVariableArray.map(e => `"${e}"`).join(',') +
')), osVersion, from: 0) >= 0) AND (indexOf(toString(array(' +
overridesVariableArray.map(e => `"${e}"`).join(',') +
')), "}", from: indexOf(toString(array(' +
overridesVariableArray.map(e => `"${e}"`).join(',') +
')), osVersion, from: 0)) >= 0)), substring( toString(array(' +
overridesVariableArray.map(e => `"${e}"`).join(',') +
')), from: ( (indexOf(toString(array(' +
overridesVariableArray.map(e => `"${e}"`).join(',') +
')), osVersion, from: 0) + stringLength(osVersion) + 5) ), to: indexOf(toString(array(' +
overridesVariableArray.map(e => `"${e}"`).join(',') +
')), "}", from: indexOf(toString(array(' +
overridesVariableArray.map(e => `"${e}"`).join(',') +
')), osVersion, from: 0)) - 2 ), else: null ) | fieldsAdd timeBeforeObsolescence = toTimestamp(if(isNotNull(`Extended Support`), `Extended Support`, else: event.eol)) - now() | fields Host = entity.name, `Management Zones` = managementZones, `Tags` = tags, OS = event.os, `Running Version` = event.currentVersion, `Full Name` = osVersion, LTS = event.lts, Cycle = event.currentCycle, `Cycle Published At` = substring(event.currentCyclePublishedAt, to:10), `End of Life` = event.eol, `Extended Support`, `Time Before Obsolescence` = timeBeforeObsolescence, `Latest Version` = event.latestVersion, `Latest Version Published at` = substring(event.latestVersionPublishedAt, to:10), Link = event.link, id, key = event.key | filter `Time Before Obsolescence` > toDuration(-7 * 24 * 60 * 60 * 1000000000) AND `Time Before Obsolescence` < toDuration(90 * 24 * 60 * 60 * 1000000000) | fieldsAdd lastAlert = lookup([ fetch events, from: -30d | filter dt.system.bucket == "default_davis_custom_events" | filter source == "software-obsolescence-management.os-alert" | sort timestamp DESC ], sourceField:id, lookupField:dt.source_entity) | limit 20000'
}
};
// console.log('DQL query:')
// console.log(query);
let res = await queryExecutionClient.queryExecute(query);
// console.log(res);
res = await queryExecutionClient.queryPoll({
requestToken: res.requestToken,
requestTimeoutMilliseconds: 30000
});
if(res.result && res.result.records) {
console.log("Soon-to-be-obsolete Operating Systems pulled successfully.");
const soonObsoleteEntities = {'0': [], '30': []};
for(let entity of res.result.records) {
if(entity["Time Before Obsolescence"] < 0) {
if(alertThresholds['0']) soonObsoleteEntities['0'].push(entity);
} else if(entity["Time Before Obsolescence"] < 30 * 24 * 60 * 60 * 1000000000) {
if(alertThresholds['30']) soonObsoleteEntities['30'].push(entity);
}
}
console.log("Sorted soon-to-be-obsolete Operating Systems:");
console.log(soonObsoleteEntities);
// From the full list of entities that will soon be obsolete, filter the ones that pass the management zone and tag restrictions and build the corresponding events
const filteredEvents = [];
for(let threshold of Object.keys(soonObsoleteEntities)) {
if(['CUSTOM_INFO', 'CUSTOM_ALERT'].includes(alertThresholds[threshold])) {
for(let entity of soonObsoleteEntities[threshold]) {
let matchedManagementZones = 0;
for(let managementZone of entity['Management Zones']) if(alertManagementZoneRestrictions.includes(managementZone)) matchedManagementZones++;
let matchedTags = 0;
for(let tag of entity['Tags']) if(alertTagRestrictions.includes(tag)) matchedTags++;
if(
(alertManagementZoneRestrictions.length === 0 || matchedManagementZones > 0) &&
(alertTagRestrictions.length === 0 || matchedTags > 0) &&
((!entity['lastAlert'] || !entity['lastAlert']['Max Remaining Days Before Obsolescence'] || entity['lastAlert']['key'] !== entity['key']) || parseInt(threshold) < parseInt(entity['lastAlert']['Max Remaining Days Before Obsolescence']))
) {
// Clean up output before saving the event
delete entity['Management Zones'];
delete entity['Tags'];
const id = entity['id'];
delete entity['id'];
const host = entity['Host'];
delete entity['Host'];
entity['Full OS Name'] = entity['Full Name'];
delete entity['Full Name'];
delete entity['Time Before Obsolescence'];
delete entity['lastAlert'];
entity['Max Remaining Days Before Obsolescence'] = parseInt(threshold);
// Add source for DQL lookup on those events
entity['source'] = 'software-obsolescence-management.os-alert';
const event = {
title: (threshold === '0' ? `${entity.OS} ${entity['Running Version']} is now obsolete` : `${entity.OS} ${entity['Running Version']} will become obsolete within ${threshold} day${parseInt(threshold) > 0 ? 's' : ''}`) + ` on host ${host}`,
eventType: alertThresholds[threshold],
entitySelector: `type(HOST),entityId(${id})`,
properties: entity
};
filteredEvents.push(event);
}
}
}
}
console.log("Events for soon-to-be-obsolete Operating Systems that match all restrictions and were not already previously raised:");
console.log(filteredEvents);
// Ingest events that matches all potential restrictions
for(let event of filteredEvents) {
try {
await eventsClient.createEvent({
body: event,
});
console.log("Event ingested successfully");
// console.log(event);
} catch (error) {
console.error("Error ingesting event:");
console.error(error);
}
}
console.log('The obsolescence alerting worker completed')
} else {
throw Error(`DQL query timed out`);
}
} catch (error) {
console.error("Error while pulling detected operating systems:", error);
throw error;
}
} else {
console.log(`All alert thresholds are deactivated. The alerting worker will not run.`)
}
}
//--------------------------------- ↓ Utilities for refreshing OS data
↓ ---------------------------------
let eolTechnologies;
async function getFreshOsData(osVersion) {
const cleanOsVersion = osVersion.substring(0, osVersion.indexOf('(') > -1 ? osVersion.indexOf('(') : osVersion.length);
console.log(cleanOsVersion);
// Extract the build number (digits and dots) from any string that could be prefixed by tags or product name; Or after 'ver. ' for Windows.
let version;
let windows = false;
if(cleanOsVersion.indexOf('ver. ') > -1) { // Windows
windows = true;
version = cleanOsVersion.substring(cleanOsVersion.indexOf('ver. ') + 5, cleanOsVersion.length);
} else if(cleanOsVersion.match(/\b\d+(\.\d+)*\b/g)) {
version = cleanOsVersion.match(/\b\d+(\.\d+)*\b/g)[0];
} else {
version = null;
}
console.log(version);
let os;
if(windows) {
os = cleanOsVersion.substring(0, cleanOsVersion.indexOf(cleanOsVersion.match(/\b\d+(\.\d+)*\b/g)[0]) - 1)
} else {
os = version === null ? cleanOsVersion : cleanOsVersion.substring(0, cleanOsVersion.indexOf(version) - 1);
}
console.log(os);
let data;
let matchedEolTechnologies = [];
eolTechnologies.forEach(eolTechnology => {
let score = 0;
// Add points thanks to the manual technologyToProductSlugMap
// if(technologyToProductSlugMap[technology] === eolTechnology.slug) score = score + 10;
// Scoring based on product slug versus os
if(os.toLowerCase().match(/[a-z]+/g).join('') === eolTechnology.slug.match(/[a-z]+/g).join('')) score = score + 10;
eolTechnology.slug.split('-').forEach(eolTechSlugSection => {
if(eolTechSlugSection.length > 1) {
if(os.toLowerCase().split(' ').includes(eolTechSlugSection)) score++;
if(os.toLowerCase().split(' ').includes(eolTechSlugSection) && eolTechnology.slug.split('-').length === 1 && eolTechnologies.filter(e => e.slug.includes(eolTechSlugSection)).length < 3) score++;
}
});
// Scoring based on product name versus technology
if(os.toLowerCase().match(/[a-z]+/g).join('') === eolTechnology.name.toLowerCase().match(/[a-z]+/g).join('')) score = score + 10;
eolTechnology.name.split(' ').forEach(eolTechNameSection => {
eolTechNameSection = eolTechNameSection.toLowerCase();
if(eolTechNameSection.length > 1 && eolTechNameSection !== 'from') {
if(os.toLowerCase().split(' ').includes(eolTechNameSection)) score++;
if(os.toLowerCase().split(' ').includes(eolTechNameSection) && eolTechnology.name.split(' ').length === 1 && eolTechnologies.filter(e => e.name.toLowerCase().includes(eolTechNameSection)).length < 3) score++;
}
});
if(score > 2) {
matchedEolTechnologies.push({
product: eolTechnology.slug,
score: score
});
}
});
matchedEolTechnologies.sort(function (a, b) {
if (a.score < b.score) {
return 1;
}
if (a.score > b.score) {
return -1;
}
return 0;
});
console.log(matchedEolTechnologies);
if(matchedEolTechnologies[0]) {
try {
console.log('Pulling EOL API for cycle details');
const cycles = await fetch(`https://endoflife.date/api/${matchedEolTechnologies[0].product}.json`).then((response) => response.json());
data = {
os: os,
currentVersion: version,
key: osVersion,
latestVersion: cycles[0].latest,
latestVersionPublishedAt: cycles[0].latestReleaseDate,
link: cycles[0].link
};
// version = version.match(/\b\d[\d.]*\d\b/g).length > 0 ? version.match(/\b\d[\d.]*\d\b/g)[0] : version; // Extrat the build number (digits and dots) from any string that could be prefixed by tags or product name; Defaults to its original value.
console.log(parseInt(version));
console.log(parseInt(cycles[0].latest));
if(version !== null) {
const candidateCycles = windows ? cycles.filter(e => version === e.latest) : cycles.filter(e => version.substring(0, e.cycle.length) === e.cycle);
if(candidateCycles.length > 0) {
candidateCycles.sort(function (a, b) {
if (a.cycle.length < b.cycle.length) {
return 1;
}
if (a.cycle.length > b.cycle.length) {
return -1;
}
return 0;
});
data.currentCycle = candidateCycles[0].cycle;
data.currentCyclePublishedAt = candidateCycles[0].releaseDate;
data.lts = candidateCycles[0].lts;
data.eol = candidateCycles[0].eol;
}
}
} catch(e) {
console.log(e);
}
}
return data;
}
//--------------------------------- ↓ Utilities for refreshing
Technology data ↓ ---------------------------------
const technologyToProductSlugMap = {
'SPRING': 'spring-boot',
'JAVA': 'openjdk-builds-from-oracle'
};
async function getFreshTechnologyData(technology, edition, version) {
let data;
let matchedEolTechnologies = [];
eolTechnologies.forEach(eolTechnology => {
let score = 0;
// Add points thanks to the manual technologyToProductSlugMap
if(technologyToProductSlugMap[technology] === eolTechnology.slug) score = score + 10;
// Scoring based on product slug versus technology
if(technology.toLowerCase().match(/[a-z]+/g).join('') === eolTechnology.slug.match(/[a-z]+/g).join('')) score = score + 10;
eolTechnology.slug.split('-').forEach(eolTechSlugSection => {
if(eolTechSlugSection.length > 1) {
if(technology.toLowerCase().includes(eolTechSlugSection)) score++;
if(technology.toLowerCase().includes(eolTechSlugSection) && eolTechnology.slug.split('-').length === 1 && eolTechnologies.filter(e => e.slug.includes(eolTechSlugSection)).length < 3) score++;
}
});
// Scoring based on product name versus technology
if(technology.toLowerCase().match(/[a-z]+/g).join('') === eolTechnology.name.toLowerCase().match(/[a-z]+/g).join('')) score = score + 10;
eolTechnology.name.split(' ').forEach(eolTechNameSection => {
eolTechNameSection = eolTechNameSection.toLowerCase();
if(eolTechNameSection.length > 1 && eolTechNameSection !== 'from') {
if(technology.toLowerCase().includes(eolTechNameSection)) score++;
if(technology.toLowerCase().includes(eolTechNameSection) && eolTechnology.name.split(' ').length === 1 && eolTechnologies.filter(e => e.name.toLowerCase().includes(eolTechNameSection)).length < 3) score++;
}
});
if(score > 2) {
matchedEolTechnologies.push({
product: eolTechnology.slug,
score: score
});
}
});
matchedEolTechnologies.sort(function (a, b) {
if (a.score < b.score) {
return 1;
}
if (a.score > b.score) {
return -1;
}
return 0;
});
// console.log(matchedEolTechnologies);
if(matchedEolTechnologies[0]) {
try {
const cycles = await fetch(`https://endoflife.date/api/${matchedEolTechnologies[0].product}.json`).then((response) => response.json());
if(!cycles || cycles.length === 0) throw Error(`Invalid endoflife.date API response`);
data = {
technology: technology,
edition: edition,
currentVersion: version,
key: `${technology}:${edition}:${version}`,
latestVersion: cycles[0].latest,
latestVersionPublishedAt: cycles[0].latestReleaseDate,
link: cycles[0].link
};
version = version.match(/\b\d+(\.\d+)*\b/g) ? version.match(/\b\d+(\.\d+)*\b/g)[0] : null; // Extrat the build number (digits and dots) from any string that could be prefixed by tags or product name; Defaults to its original value.
if(version) {
console.log(parseInt(version));
console.log(parseInt(cycles[0].latest));
if(parseInt(version) > parseInt(cycles[0].latest)) {
data = null;
throw Error(`The latest release of the retrieved EOL product is lower than the detected technology's current version`);
}
const candidateCycles = cycles.filter(e => version.substring(0, e.cycle.length) === e.cycle);
if(candidateCycles.length > 0) {
candidateCycles.sort(function (a, b) {
if (a.cycle.length < b.cycle.length) {
return 1;
}
if (a.cycle.length > b.cycle.length) {
return -1;
}
return 0;
});
data.currentCycle = candidateCycles[0].cycle;
data.currentCyclePublishedAt = candidateCycles[0].releaseDate;
data.lts = candidateCycles[0].lts;
data.eol = candidateCycles[0].eol;
}
}
} catch(e) {
console.log(e);
}
}
return data;
}
//--------------------------------- ↓ Utilities for refreshing library
data ↓ ---------------------------------
const typePackageManagerMap = {
'DOTNET': 'NUGET',
'NODE_JS': 'NPM',
'JAVA': 'MAVEN',
'GO': 'GO'
}
async function getFreshLibraryData(packageManager, library, version) {
let data;
let releases;
// Try to retrieve the list of know releases for that library. If response is not JSON/empty, it will stop the processing of that library version
try {
releases = await fetch(`https://api.deps.dev/v3/systems/${packageManager}/packages/${encodeURIComponent(library)}`).then((response) => response.json());
} catch(e) {
console.error(`No releases data found for ${library}:${version}`);
}
if(releases && releases.versions && releases.versions.filter(e => e.isDefault === true)[0]) {
// console.log(releases);
data = {
packageManager: packageManager,
library: library,
currentVersion: version,
key: `${library}:${version}`
};
if(releases && releases.versions && releases.versions.filter(e => e.isDefault === true)[0].versionKey.version) data.latestStableVersion = releases.versions.filter(e => e.isDefault === true)[0].versionKey.version;
if(releases && releases.versions && releases.versions.filter(e => e.isDefault === true)[0].publishedAt) data.latestStableVersionPublishedAt = releases.versions.filter(e => e.isDefault === true)[0].publishedAt;
try {
const versionDetails = await fetch(`https://api.deps.dev/v3/systems/${packageManager}/packages/${encodeURIComponent(library)}/versions/${version}`).then((response) => response.json());
// console.log(versionDetails);
if(versionDetails && versionDetails.publishedAt) data.currentVersionPublishedAt = versionDetails.publishedAt;
if(versionDetails && versionDetails.links && versionDetails.links.filter(e => e.label === 'ORIGIN')[0]) data.link = versionDetails.links.filter(e => e.label === 'ORIGIN')[0].url;
if(versionDetails && versionDetails.licenses && versionDetails.licenses.length > 0) data.licenses = versionDetails.licenses.join(', ');
} catch(e) {
console.log(`No version details found for ${library}:${version}`);
}
return data;
}
}
async function refreshOsData() {
//--------------------------------- ↓ Refresh OS data ↓ ---------------------------------
try {
let detectedTechnologies = [];
// Download the full list of EOL product slugs
eolTechnologies = await fetch('https://endoflife.date/api/all.json').then((response) => response.json());
eolTechnologies = eolTechnologies.map(e => {
return { slug: e };
});
// Try to augment them with the corresponding product name, scraping the homepage's navigation menu (product name is not available via API)
try {
let eolNavMenu = await fetch('https://endoflife.date').then((response) => response.text());
eolNavMenu = eolNavMenu.substring(eolNavMenu.indexOf('<li class="nav-list-item">'), eolNavMenu.indexOf('</ul>', eolNavMenu.indexOf('"nav-list"')));
// console.log(eolNavMenu);
const productMap = eolNavMenu.split('</li>').map(e => {
return {
slug: e.substring(e.indexOf('href="/') + 7, e.indexOf('"', e.indexOf('href="/') + 7)),
name: e.substring(e.indexOf('">', e.indexOf('<a')) + 2, e.indexOf('</a>'))
};
});
// console.log(productMap);
eolTechnologies.forEach(e => {
try {
e.name = productMap.filter(el => el.slug === e.slug)[0].name;
} catch(error) {}
});
} catch(e) {
console.log(`Error while trying to augment the technology slugs by their corresponding product name`);
}
// console.log(eolTechnologies);
try {
let res = await queryExecutionClient.queryExecute({
body: {
query: `fetch dt.entity.host, from: -15m | fieldsAdd osVersion, softwareObsolescenceManagement = entity.name | summarize by:{osVersion}, count = count() | fieldsAdd result = lookup([ fetch events, from: -7d | filter dt.system.bucket == "default_davis_custom_events" | filter event.name == "software-obsolescence-management.os-info" | sort timestamp DESC ], sourceField:osVersion, lookupField:key ) | fieldsFlatten result, prefix:"event." | filter isNull(event.timestamp) | fieldsAdd random = random() | sort random ASC | fields osVersion | limit 60`
}
});
// console.log(res);
const requestToken = res.requestToken;
res = await queryExecutionClient.queryPoll({
requestToken: res.requestToken,
requestTimeoutMilliseconds: 60000
});
if(res.result && res.result.records) {
console.log("Detected OS pulled successfully.");
detectedTechnologies = res.result.records;
} else {
throw Error(`DQL query timed out`);
}
} catch (error) {
console.error("Error while pulling detected OS:", error);
throw error;
}
for(let detectedTechnology of detectedTechnologies.slice(0, 60)) {
// console.log(detectedTechnology);
if(detectedTechnology.osVersion) {
const technologyData = await getFreshOsData(detectedTechnology.osVersion);
if(technologyData) {
console.log(`Technology data pulled successfully for ${detectedTechnology.osVersion}`);
const event = {
title: "software-obsolescence-management.os-info",
eventType: "CUSTOM_INFO",
properties: technologyData
};
console.log(event);
try {
await eventsClient.createEvent({
body: event,
});
console.log("Event ingested successfully");
// console.log(event);
} catch (error) {
console.error("Error ingesting event");
// console.error(event);
}
} else {
console.error(`No technology data found for ${detectedTechnology.osVersion}`);
}
}
}
} catch(e) {
console.log(e);
}
}
async function refreshTechnologyData() {
//--------------------------------- ↓ Refresh Technology data ↓ ---------------------------------
try {
let detectedTechnologies = [];
// Download the full list of EOL product slugs
eolTechnologies = await fetch('https://endoflife.date/api/all.json').then((response) => response.json());
eolTechnologies = eolTechnologies.map(e => {
return { slug: e };
});
// Try to augment them with the corresponding product name, scraping the homepage's navigation menu (product name is not available via API)
try {
let eolNavMenu = await fetch('https://endoflife.date').then((response) => response.text());
eolNavMenu = eolNavMenu.substring(eolNavMenu.indexOf('<li class="nav-list-item">'), eolNavMenu.indexOf('</ul>', eolNavMenu.indexOf('"nav-list"')));
// console.log(eolNavMenu);
const productMap = eolNavMenu.split('</li>').map(e => {
return {
slug: e.substring(e.indexOf('href="/') + 7, e.indexOf('"', e.indexOf('href="/') + 7)),
name: e.substring(e.indexOf('">', e.indexOf('<a')) + 2, e.indexOf('</a>'))
};
});
// console.log(productMap);
eolTechnologies.forEach(e => {
try {
e.name = productMap.filter(el => el.slug === e.slug)[0].name;
} catch(error) {}
});
} catch(e) {
console.log(`Error while trying to augment the technology slugs by their corresponding product name`);
}
// console.log(eolTechnologies);
try {
let res = await queryExecutionClient.queryExecute({
body: {
query: `fetch dt.entity.process_group_instance, from: -15m | fieldsRename Process = entity.name | fieldsAdd softwareTechnologies, softwareObsolescenceManagement = Process | expand softwareTechnologies | parse softwareTechnologies, "'type:' LD:Technology ',edition:' LD:Edition ',version:' LD:Version" | fields Technology, Edition, Version | filter isNotNull(Technology) AND Technology != "null" | fieldsAdd key = concat(Technology, ":", Edition, ":", Version) | fieldsAdd result = lookup([ fetch events, from: -7d | filter dt.system.bucket == "default_davis_custom_events" | filter event.name == "software-obsolescence-management.technology-info" ], sourceField:key, lookupField:key ) | fieldsFlatten result, prefix:"event." | filter isNull(event.timestamp) | summarize by:{Technology, Edition, Version, key}, count = count() | fieldsAdd random = random() | sort random ASC | fields Technology, Edition, Version, key | limit 60`
}
});
// console.log(res);
res = await queryExecutionClient.queryPoll({
requestToken: res.requestToken,
requestTimeoutMilliseconds: 60000
});
if(res.result && res.result.records) {
console.log("Detected technologies pulled successfully.");
detectedTechnologies = res.result.records;
} else {
throw Error(`DQL query timed out`);
}
} catch (error) {
console.error("Error while pulling detected technologies:", error);
throw error;
}
for(let detectedTechnology of detectedTechnologies.slice(0, 60)) {
// console.log(detectedTechnology);
const technologyData = await getFreshTechnologyData(detectedTechnology.Technology, detectedTechnology.Edition, detectedTechnology.Version);
if(technologyData) {
console.log(`Technology data pulled successfully for ${detectedTechnology.key}`);
const event = {
title: "software-obsolescence-management.technology-info",
eventType: "CUSTOM_INFO",
properties: technologyData
};
try {
await eventsClient.createEvent({
body: event,
});
console.log("Event ingested successfully");
// console.log(event);
} catch (error) {
console.error("Error ingesting event");
// console.error(event);
}
} else {
console.error(`No technology data found for ${detectedTechnology.key}`);
}
}
} catch(e) {
console.log(e);
}
}
async function refreshLibraryData() {
//--------------------------------- ↓ Refresh Library data ↓ ---------------------------------
try {
let softwareComponents = [];
try {
let res = await queryExecutionClient.queryExecute({
body: {
query: 'fetch dt.entity.software_component, from: -15m | fieldsAdd softwareComponentFileName, softwareObsolescenceManagement = entity.name | fieldsAdd lastColonIndex = lastIndexOf(entity.name, ":") | fieldsAdd Type = softwareComponentType | fieldsAdd Library = substring(entity.name, to:lastColonIndex) | fieldsAdd Version = softwareComponentVersion | fieldsAdd result = lookup([ fetch events, from: -7d | filter dt.system.bucket == "default_davis_custom_events" | filter event.name == "software-obsolescence-management.library-info" ], sourceField:entity.name, lookupField:key ) | fieldsFlatten result, prefix:"event." | filter isNull(event.timestamp) | summarize by:{Type, Library, Version, entity.name}, count = count() | fieldsAdd random = random() | sort random ASC | fields Type, Library, Version, entity.name | limit 60'
}
});
// console.log(res);
res = await queryExecutionClient.queryPoll({
requestToken: res.requestToken,
requestTimeoutMilliseconds: 60000
});
if(res.result && res.result.records) {
console.log("Software components pulled successfully.");
softwareComponents = res.result.records;
} else {
throw Error(`DQL query timed out`);
}
} catch (error) {
console.error("Error while pulling software components:", error);
throw error;
}
// console.log(softwareComponents);
for(let softwareComponent of softwareComponents) {
const libraryData = await getFreshLibraryData(typePackageManagerMap[softwareComponent.Type], softwareComponent.Library, softwareComponent.Version);
if(libraryData) {
console.log(`Library data pulled successfully for ${softwareComponent['entity.name']}`);
const event = {
title: "software-obsolescence-management.library-info",
eventType: "CUSTOM_INFO",
properties: libraryData
};
// console.log(event);
try {
await eventsClient.createEvent({
body: event,
});
console.log("Event ingested successfully");
// console.log(event);
} catch (error) {
console.error("Error ingesting event:", error);
// console.error(event);
}
} else {
console.error(`No library data found for ${softwareComponent['entity.name']}`);
}
}
} catch(e) {
console.log(e);
}
}
export default async function () {
refreshOsData();
console.log(`Refreshing OS Data...`);
refreshTechnologyData();
console.log(`Refreshing Technology Data...`);
refreshLibraryData();
console.log(`Refreshing Library Data...`);
raiseProactiveAlerts();
}
position:
x: 0
y: 1
predecessors: []
description: ""
trigger:
schedule:
rule: null
trigger:
type: interval
intervalMinutes: 2
betweenStart: 04:00
betweenEnd: 06:00
timezone: UTC
isActive: true
isFaulty: false
nextExecution: 2025-03-15T04:00:00.000Z
filterParameters:
earliestStart: 2025-03-13
earliestStartTime: 00:08
inputs: {}
schemaVersion: 3
result: null
input: {}
hourlyExecutionLimit: 1000
type: STANDARD